leetcode211. 添加與搜索單詞 - 數據結構設計

設計一個支持以下兩種操作的數據結構:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正則表達式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一個字母。

參考leetcode208. 實現 Trie (前綴樹)

class WordDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.trie = {}

    def addWord(self, word: str) -> None:
        """
        Adds a word into the data structure.
        """
        node = self.trie
        for c in word:
            node = node.setdefault(c, {})
        node['end'] = 1

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        """
        return self.helper(word, self.trie)

    def helper(self, word, root):
        if not word:
            return root.get('end', 0) == 1
        if not root:
            return False
        node = root
        for c in word:
            if c != '.':
                if c not in node:
                    return False
                return self.helper(word[1:], node[c])
            else:
                for k, v in node.items():
                    if k != 'end' and self.helper(word[1:], node[k]):
                        return True
                return False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章