码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-10-02 18:47:00      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:from   turn   ==   led   结构   ini   cti   span   structure   

题目描述:

技术图片

 

 方法一:

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-添加与搜索单词-数据结构设计

标签:from   turn   ==   led   结构   ini   cti   span   structure   

原文地址:https://www.cnblogs.com/oldby/p/11617753.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!