Leetcode 211.添加與搜索單詞 - 數據結構設計(Add and Search Word - Data structure design)

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

1 題目描述(Leetcode題目鏈接

  設計一個支持以下兩種操作的數據結構:

void addWord(word)
bool search(word)

search(word) 可以搜索文字或正則表達式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一個字母。

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

說明:你可以假設所有單詞都是由小寫字母 a-z 組成的

2 題解

  本題爲字典樹的基本操作的實現,可以參照第208題,這裏由於存在通配符,所以如果遇到通配符就需要遍歷當前層的所有子節點,用深度優先搜索遞歸實現就可以了。

class TreeNode:

    def __init__(self):
        self.children = collections.defaultdict(TreeNode)
        self.end = False

class WordDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TreeNode()


    def addWord(self, word: str) -> None:
        """
        Adds a word into the data structure.
        """
        node = self.root
        for char in word:
            node = node.children[char]
        node.end = True


    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.
        """
        length = len(word)

        def dfs(node, i):
            if i == length:
                return node.end
            if word[i] != ".":
                node = node.children.get(word[i])
                if node:
                    return dfs(node, i + 1)
                return False
            else:
                for char in node.children:
                    if dfs(node.children[char], i + 1):
                        return True
                return False

        return dfs(self.root, 0)




# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章