1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
design-search-autocomplete-system.py 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 7年前 . add complexity
# Time: O(p^2), p is the length of the prefix
# Space: O(p * t + s), t is the number of nodes of trie
# , s is the size of the sentences
import collections
class TrieNode(object):
def __init__(self):
self.__TOP_COUNT = 3
self.infos = []
self.leaves = {}
def insert(self, s, times):
cur = self
cur.add_info(s, times)
for c in s:
if c not in cur.leaves:
cur.leaves[c] = TrieNode()
cur = cur.leaves[c]
cur.add_info(s, times)
def add_info(self, s, times):
for p in self.infos:
if p[1] == s:
p[0] = -times
break
else:
self.infos.append([-times, s])
self.infos.sort()
if len(self.infos) > self.__TOP_COUNT:
self.infos.pop()
class AutocompleteSystem(object):
def __init__(self, sentences, times):
"""
:type sentences: List[str]
:type times: List[int]
"""
self.__trie = TrieNode()
self.__cur_node = self.__trie
self.__search = []
self.__sentence_to_count = collections.defaultdict(int)
for sentence, count in zip(sentences, times):
self.__sentence_to_count[sentence] = count
self.__trie.insert(sentence, count)
def input(self, c):
"""
:type c: str
:rtype: List[str]
"""
result = []
if c == '#':
self.__sentence_to_count["".join(self.__search)] += 1
self.__trie.insert("".join(self.__search), self.__sentence_to_count["".join(self.__search)])
self.__cur_node = self.__trie
self.__search = []
else:
self.__search.append(c)
if self.__cur_node:
if c not in self.__cur_node.leaves:
self.__cur_node = None
return []
self.__cur_node = self.__cur_node.leaves[c]
result = [p[1] for p in self.__cur_node.infos]
return result
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助