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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章