


可以使用 Trie(前缀树)来高效存储和检索前缀匹配的产品,同时在 Trie 的每个节点存储最多 3 个字典序最小的产品,以加速查询。以下是 Python 代码实现:
from typing import List
import bisect
class TrieNode:
def __init__(self):
self.children = {}
self.suggestions = []
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
if len(node.suggestions) < 3:
bisect.insort(node.suggestions, word)
if len(node.suggestions) > 3:
node.suggestions.pop()
def search(self, prefix: str) -> List[List[str]]:
node = self.root
result = []
for ch in prefix:
if ch in node.children:
node = node.children[ch]
result.append(node.suggestions)
else:
result.append([])
node = TrieNode() # Create a dummy node to continue empty suggestions
return result
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
trie = Trie()
for product in sorted(products):
trie.insert(product)
return trie.search(searchWord)
def printSuggestions(self, products: List[str], searchWord: str):
suggestions = self.suggestedProducts(products, searchWord)
for i, s in enumerate(suggestions):
print(f"After typing '{searchWord[:i+1]}': {s}")
# 示例
sol = Solution()
products = ["mobile", "mouse", "moneypot", "monitor", "mousepad"]
searchWord = "mouse"
print(sol.suggestedProducts(products, searchWord))
sol.printSuggestions(products, searchWord)
代码解析:
-
TrieNode 结构:
children:存储子节点(即下一个字符)。suggestions:存储当前节点下最多 3 个按字典序排列的产品。
-
Trie 结构:
insert方法:将products按字典序排序后插入Trie,每个节点维护最多 3 个推荐产品。search方法:查询searchWord的前缀匹配产品。
-
Solution 类:
- 先对
products排序。 - 逐个插入
Trie。 - 依次搜索
searchWord的每个前缀,返回推荐列表。
- 先对
这样能高效地获取推荐产品列表。你可以试试不同的输入!🚀
1791

被折叠的 条评论
为什么被折叠?



