208. 实现 Trie (前缀树)、211. 添加与搜索单词 - 数据结构设计

208. 实现 Trie (前缀树):

思路:

class Trie:
    # 字典树,就是使用单词的每个字符作为键,后续字符字典作为值
    def __init__(self):
        # 根是一个字典
        self.root = {}  

    def insert(self, word: str) -> None:
        # 依次插入子节点,若不存在则创建
        node =self.root
        for c in word:
            if c not in node.keys():
                node[c] = {}   
            node = node[c]  
        
        node['#'] = {}

    def search(self, word: str) -> bool:
        # 若每个字符都能找到,且以‘is_word’结尾,则返回True
        node =self.root
        for c in word:
            if c in node.keys():
                node = node[c]
            else:
                return False

        if '#' in node.keys():
            return True
        else:
            return False
        
    def startsWith(self, prefix: str) -> bool:
        # 若每个字符都能找到,则返回True
        node =self.root
        for c in prefix:
            if c in node.keys():
                node = node[c]
            else:
                return False
        
        return True

在这里插入图片描述

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

思路:
对于遇到“.”的情况,则是对所有的子节点递归地取寻找,只要有真则真。

class WordDictionary:

    def __init__(self):
        self.root = {}

    def addWord(self, word: str) -> None:
        node = self.root
        for c in word:
            if c not in node.keys():
                node[c] = {}
            node = node[c]

        node['#'] = {}  # 表示叶节点

    def search(self, word: str) -> bool:
        def helper(word, node):
            if not word: # 如果word为空并且tree到达末尾,则搜索成功
                if "#" in node: 
                    return True
                return False
            if word[0] == ".": # 如果word为“.”,则递归地对树的每个分支都进行搜索,只要有一个找到都认为搜索成功
                for t in node:
                    if helper(word[1:], node[t]):
                        return True
            elif word[0] in node: # 如果当前字符匹配,则对树的下个节点进行搜索,找到则认为搜索成功
                if helper(word[1:], node[word[0]]):
                    return True
            return False          # 都没找到,认为失败
        node = self.root
        return helper(word,node)

在这里插入图片描述

发布了119 篇原创文章 · 获赞 4 · 访问量 5473

猜你喜欢

转载自blog.csdn.net/qq_27921205/article/details/104388972
今日推荐