Note: The Listed platform will permanently shut down December 31, 2026. Your data published on Listed will still be available in your personal Standard Notes account. Learn more

if helper return vs return helper

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)


You'll only receive email when they publish something new.

More from LeetCode
All posts