leetcode-211-添加与搜索单词-数据结构设计

Posted 真不知道叫啥好

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-211-添加与搜索单词-数据结构设计相关的知识,希望对你有一定的参考价值。

题目描述:

 

 方法一:

class WordDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        #from collections import defaultdict
        self.lookup = {}

    def addWord(self, word: str) -> None:
        """
        Adds a word into the data structure.
        """
        tree = self.lookup
        for a in word:
            if a not in tree:
                tree[a] = {}
            tree = tree[a]
        tree["#"] = {}

    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.
        """
        def helper(word, tree):
            if not word:
                if "#" in tree:
                    return True
                return False
            if word[0] == ".":
                for t in tree:
                    if helper(word[1:], tree[t]):
                        return True
            elif word[0] in tree:
                if helper(word[1:], tree[word[0]]):
                    return True
            return False

        return helper(word,self.lookup)


# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

 

以上是关于leetcode-211-添加与搜索单词-数据结构设计的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-211-添加与搜索单词-数据结构设计

LeetCode 211.添加与搜索单词, swift

leetcode 211. 添加与搜索单词 - 数据结构设计 解题报告

LeetCode211. 添加与搜索单词 - 数据结构设计(相关话题:Trie前缀树)

LeetCode211. 添加与搜索单词 - 数据结构设计(相关话题:Trie前缀树)

[leetcode]211. Add and Search Word - Data structure design添加查找单词 - 数据结构设计