File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Solution/1268. Search Suggestions System Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ class Trie :
2+ def __init__ (self ):
3+ self .children : List [Union [Trie , None ]] = [None ] * 26
4+ self .v : List [int ] = []
5+
6+ def insert (self , w , i ):
7+ node = self
8+ for c in w :
9+ idx = ord (c ) - ord ('a' )
10+ if node .children [idx ] is None :
11+ node .children [idx ] = Trie ()
12+ node = node .children [idx ]
13+ if len (node .v ) < 3 :
14+ node .v .append (i )
15+
16+ def search (self , w ):
17+ node = self
18+ ans = [[] for _ in range (len (w ))]
19+ for i , c in enumerate (w ):
20+ idx = ord (c ) - ord ('a' )
21+ if node .children [idx ] is None :
22+ break
23+ node = node .children [idx ]
24+ ans [i ] = node .v
25+ return ans
26+
27+
28+ class Solution :
29+ def suggestedProducts (
30+ self , products : List [str ], searchWord : str
31+ ) -> List [List [str ]]:
32+ products .sort ()
33+ trie = Trie ()
34+ for i , w in enumerate (products ):
35+ trie .insert (w , i )
36+ return [[products [i ] for i in v ] for v in trie .search (searchWord )]
You can’t perform that action at this time.
0 commit comments