File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ # Time: O((n + q) * l)
2+ # Space: O(t)
3+
4+ # trie
5+ class Solution (object ):
6+ def stringIndices (self , wordsContainer , wordsQuery ):
7+ """
8+ :type wordsContainer: List[str]
9+ :type wordsQuery: List[str]
10+ :rtype: List[int]
11+ """
12+ INF = float ("INF" )
13+ class Trie (object ):
14+ def __init__ (self ):
15+ self .__nodes = []
16+ self .__mns = []
17+ self .__new_node ()
18+
19+ def __new_node (self ):
20+ self .__nodes .append ([- 1 ]* 26 )
21+ self .__mns .append ((INF , INF ))
22+ return len (self .__nodes )- 1
23+
24+ def add (self , i , w ):
25+ curr = 0
26+ self .__mns [curr ] = min (self .__mns [curr ], (len (w ), i ))
27+ for c in reversed (w ):
28+ x = ord (c )- ord ('a' )
29+ if self .__nodes [curr ][x ] == - 1 :
30+ self .__nodes [curr ][x ] = self .__new_node ()
31+ curr = self .__nodes [curr ][x ]
32+ self .__mns [curr ] = min (self .__mns [curr ], (len (w ), i ))
33+
34+ def query (self , w ):
35+ curr = 0
36+ for c in reversed (w ):
37+ x = ord (c )- ord ('a' )
38+ if self .__nodes [curr ][x ] == - 1 :
39+ break
40+ curr = self .__nodes [curr ][x ]
41+ return self .__mns [curr ][1 ]
42+
43+ trie = Trie ()
44+ for i , w in enumerate (wordsContainer ):
45+ trie .add (i , w )
46+ return [trie .query (w ) for w in wordsQuery ]
You can’t perform that action at this time.
0 commit comments