1 class TrieNode:
 2     def __init__(self):
 3         self.children = dict()
 4         self.words = []
 5 
 6 class Trie:
 7     def __init__(self):
 8         self.root = TrieNode()
 9     
10     def insert(self, word):
11         node = self.root
12         for char in word:
13             if char not in node.children:
14                 node.children[char] = TrieNode()
15             node = node.children[char]
16             node.words.append(word)
17             node.words.sort()
18             while len(node.words) > 3:
19                 node.words.pop()
20     
21     def search(self, word):
22         res = []
23         node = self.root
24         for char in word:
25             if char not in node.children:
26                 break
27             node = node.children[char]
28             res.append(node.words[:])
29         l_remain = len(word) - len(res)
30         for _ in range(l_remain):
31             res.append([])
32         return res
33 
34 class Solution:
35     def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
36         trie = Trie()
37         for prod in products:
38             trie.insert(prod)
39         return trie.search(searchWord)

算法思想:Trie(前缀树/字典树)

参考:https://leetcode.com/problems/search-suggestions-system/discuss/436183/Python-Trie-Solution

posted on 2020-01-14 16:38  Sempron2800+  阅读(158)  评论(0编辑  收藏  举报