字典树-676. 实现一个魔法字典-PYTHON

在这里插入图片描述

字典树-++

class MagicDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.trie = dict()  #构建字典树

    def buildDict(self, words):
        """
        Build a dictionary through a list of words
        """
        node = self.trie
        for w in words:  #遍历构建的单词列表
            for c in w:  #遍历每个单词的每个字母元素
                if c not in node:
                    node[c] = dict() #构建子字典树
                node = node[c]  
            node['#'] = {}  #单词结束符
            node = self.trie  #重置指针

    def search(self, word):
        """
        Returns if there is any word in the trie that equals to the given word after modifying exactly one character
        """
        def find(word, node):  #查找word是否存在于给出的字典树node中
            for u in word:
                if u not in node:
                    return False
                node=node[u]
            return '#' in node 

        def searchResult(word, node, diff): #递归调用自身
            if not word:
                return diff==1 and '#' in node #递归结束条件,差异为1位,并且单词结束
            res = False
            if diff: # 已有一位字符与word不同
                return find(word, node)
            for u in node:
                res |= searchResult(word[1:], node[u], 0 if word[0]==u else 1)
            return res

        return searchResult(word, self.trie, 0)

大佬代码-++

class MagicDictionary(object):

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

    def buildDict(self, dict):
        """
        Build a dictionary through a list of words
        :type dict: List[str]
        :rtype: None
        """ 
        for word in dict:
            self.lists[len(word)].append(word)
        

    def search(self, word):
        """
        Returns if there is any word in the trie that equals to the given word after modifying exactly one character
        :type word: str
        :rtype: bool
        """
        return any(sum(a!=b for a,b in zip(word, candidate)) == 1 for candidate in self.lists[len(word)])


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值