leetcode刷题笔记-tire

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sengo_GWU/article/details/82948834

211. Add and Search Word - Data structure design

class TrieNode():
    def __init__(self):
        self.children = collections.defaultdict(TrieNode)
        self.isWord = False

        
class WordDictionary(object):

    def __init__(self):
        """ 
        TrieNode:
        根节点不包含字符,除根节点外每一个节点都只包含一个字符。
        从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
        每个节点的所有子节点包含的字符都不相同。
        """
        self.root = TrieNode()  

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: void
        """
        node = self.root
        for c in word:
            node = node.children[c]
        node.isWord = True
        
    def search(self, word):
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        :type word: str
        :rtype: bool
        """
        node = self.root
        self.res = False
        self.dfs(node, word)
        return self.res
    
    def dfs(self, node, word):
        if not word:
            if node.isWord:
                self.res = True
            return
        
        if word[0] == '.':
            for n in node.children.values():
                self.dfs(n, word[1:])
        else:
            n = node.children.get(word[0])  # 不能写 node.children[word[0]] 不然会返回默认类型
            if not n:
                return
            self.dfs(n, word[1:])
        

猜你喜欢

转载自blog.csdn.net/Sengo_GWU/article/details/82948834