我正在解决Design Add and Search Words Data Structure - LeetCode,但是出现了 Time Limit Exceeded ,我应该怎么解决?哪里可以优化?
class TreeNode:
def __init__(self):
self.children = {}
self.end_of_word = False
# prefix tree
class WordDictionary:
def __init__(self):
self.root = TreeNode()
def addWord(self, word: str) -> None:
current = self.root
for c in word:
if c not in current.children:
current.children[c] = TreeNode()
current = current.children[c]
current.end_of_word = True
def search(self, word: str) -> bool:
# search using recursion
def _search(i, current):
if i == len(word) - 1:
if word[i] == '.':
for child in current.children.values():
if child.end_of_word:
return True
return False
elif word[i] in current.children:
return current.children[word[i]].end_of_word
else:
return False
if word[i] == '.':
for child in current.children.values():
if _search(i + 1, child):
return True
return False
elif word[i] in current.children:
return _search(i + 1, current.children[word[i]])
else:
return False
return _search(0, self.root)
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.