字典树-211. 添加与搜索单词 - 数据结构设计-PYTHON

在这里插入图片描述

利用字典集合,利用长度来简化比对的次数,效果还可以

class WordDictionary(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.d = collections.defaultdict(list)
        

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: None
        """
        self.d[len(word)].append(word)  #构建集合,将相同长度的单词存在同一个字典键下
        

    def search(self, word):
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        :type word: str
        :rtype: bool
        """
        #简便写法
        n = len(word)
        f = lambda s: all(map(lambda i: word[i] in {s[i], '.'}, range(n)))#匹配函数,比写正则要快不少,all为必须全部都为True才为True
        return any(map(f, self.d[n])) #any为只要之中元素有一个True最终结果就为True

        #拓展写法
        n = len(word)
        def f(s):
            print(s)
            for i in range(n):
                if word[i] not in {s[i], '.'}:
                    print(s[i])
                    return False
            return True
        for s in self.d[n]:  #从相同长度的单词中逐一取出进行比对
            if f(s):
                return True
        return False
		
		#正则写法
		return re.search(word.replace('.', '[a-z]'), self.d[len(word)])

        

递归逐一比对

class WordDictionary:

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

    def addWord(self, word):
        """
        Adds a word into the data structure.
        """
        tree = self.lookup
        for a in word:
            tree = tree.setdefault(a, {}) #返回值是插入后的当前元素
        tree["#"] = {}

        

    def search(self, word):
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        """
        #{u'b': {u'a': {u'd': {'#': {}}}}, u'm': {u'a': {u'd': {'#': {}}}}, u'd': {u'a': {u'd': {'#': {}}}}}
        def helper(word, tree):
            if not word: #word的下一个字符为空表示结束,在字典中正好也是出现了结束符那么代表匹配成功
                if "#" in tree:
                    return True #匹配成功返回True,否则代表还有更长的单词,就返回False
                return False
            if word[0] == ".": #如果第一个字符是.,跳过第一个元素对字典中每一个分支进行递归调用
                for t in tree:
                    # print(tree[t])
                    if helper(word[1:], tree[t]):
                        return True
            elif word[0] in tree: #如果第一个字符在字典的键值中,将会锁定一个tree的字典分支继续向下进行递归比对
                print(tree[word[0]])
                if helper(word[1:], tree[word[0]]):
                    return True
            return False #第一个字符就不在字典中直接返回False

        return helper(word, self.lookup)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值