leetcode 211.添加与搜索单次-数据结构设计(字典树)

题目:

请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 WordDictionary :
WordDictionary() 初始化词典对象
void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配
bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回  false 。word 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。

题目示例:

输入:
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
输出:
[null,null,null,null,false,true,true,true]
解释:
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // 返回 False
wordDictionary.search("bad"); // 返回 True
wordDictionary.search(".ad"); // 返回 True
wordDictionary.search("b.."); // 返回 True

DFS代码:

class WordDictionary:
    def __init__(self):
        self.hashmap={}#声明一个哈希表,用来储存当前保存的所有字母
        self.last=False #当前节点是否是尾节点
    def addWord(self, word: str) -> None:
        node=self
        for s in word: #每个对应节点插入到对应的哈希值中
            num=node.hashmap.get(s,0)#没有对应值
            if not num:#没有对应值
                node.hashmap[s]=WordDictionary()#对应键值实例化
            node=node.hashmap[s]#进入到对应键值里
        node.last=True
    def search(self, word: str) -> bool:
        def dfs(index,node):#输入对应键值位置
            if index==len(word):
                return node.last#看尾巴是否是尾节点
            if word[index]=='.': #如果为'.',则将所有当前键值进入DFS递归
                for num in node.hashmap.keys():
                    if dfs(index+1,node.hashmap[num]):#递归均为TRUE,返回正确结果
                        return True
            else:
                count=word[index]#否则进入对应键值实例化
                if count in node.hashmap:
                    if dfs(index+1,node.hashmap[count]):
                        return True
            return False
        return dfs(0,self)

DFS思路:

DFS深度遍历,我们在每一位输出化一个字典,如果有对应键值输入,则将对应键值实例化,同时进入对应键值,如果是末尾,则对应last置True

因为涉及到'.',所以如果当前位是点时则将所有键值递归,否则递归对应键值,只有当所有键值返回为True时,才为正确结果;如果没有键值或者均为FALSE,返回FALSE

BFS代码:

class WordDictionary:

    def __init__(self):
        self.hashmap={}
        self.last=False
    def addWord(self, word: str) -> None:
        node=self
        for s in word:
            index=ord(s)-ord('a')
            num=node.hashmap.get(index,0)#没有对应值
            if not num:#有对应值
                node.hashmap[index]=WordDictionary()#对应键值实例化
            node=node.hashmap[index]#进入到对应键值里
        node.last=True
    def search(self, word: str) -> bool:
        node=self #根节点层
        q=deque([(list(node.hashmap.keys()),node)])#当前树键值以及对应节点
        count=-1
        total=len(word)
        while q:
            count+=1
            if count==len(word):
                state=False
                while q:
                    cur,node=q.popleft()
                    state=state or node.last
                break
            if word[count]=='.':#当前键值均加入队列中
                for _ in range(len(q)):
                    cur,node=q.popleft()#cur为键值列表,node为当前节点
                    for num in cur:
                        q.append((list(node.hashmap[num].hashmap.keys()),node.hashmap[num]))
            else:
                index=ord(word[count])-ord('a')#将对应键值加入队列中
                for _ in range(len(q)):
                    cur,node=q.popleft()
                    if index in cur:
                        q.append((list(node.hashmap[index].hashmap.keys()),node.hashmap[index]))
        
        if count==len(word) and state:
            return True
        else:
            return False

BFS思路:
将所有键值进行层序遍历,如果遇到点,则将当前所有键传递到下一层,否则只传递对应键值,当层序遍历到对应长度时,查看当前所有末尾值是否为True,只有当遍历长度相同且末尾为True时,返回True

层序遍历对比深度遍历来说,要慢,必须将所有对应节点长度遍历完之后才能知道对应结果是否正确,深度遍历遍历到正确结果即可返回对应结果

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值