if helper return vs return helper
December 17, 2022•183 words
if helper return vs return helper
以这一题为例
211. 添加与搜索单词 - 数据结构设计
我们看 helper function里面有一个
if self.helper(word, node.next[i], k+1):
return True
还有一个
return self.helper(word, node.next[ch], k+1)
- 那么什么时候是
if helper return True - 什么时候是
return helper
答案是:
如例子里面
- 那么什么时候是
if helper return True
for loop里面有很多可能性,有的return True, 有的 return False
其实我关心只是,是否有一个True
- 什么时候是
return helper
就是我接下来只有一种可能,所以可以就 return helper
class Trie:
def __init__(self):
self.next = {}
self.isWord = False
class WordDictionary:
def __init__(self):
self.node = Trie()
def addWord(self, word: str) -> None:
node = self.node
for ch in word:
if ch not in node.next:
node.next[ch] = Trie()
node = node.next[ch]
node.isWord = True
def search(self, word: str) -> bool:
node = self.node
k = 0
return self.helper(word, node, k)
def helper(self, word, node, k):
if k == len(word):
return node.isWord
ch = word[k]
if ch == ".":
for i in node.next:
if self.helper(word, node.next[i], k+1):
return True
return False
else:
if ch not in node.next:
return False
else:
return self.helper(word, node.next[ch], k+1)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)