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


    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

    提示:

    • 1 <= word.length <= 25
    • addWord 中的 word 由小写英文字母组成
    • search 中的 word 由 ‘.’ 或小写英文字母组成
    • 最多调用 104 次 addWord 和 search

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/summary-ranges
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    1.

    时间
    2808ms
    击败 45.89%使用 Python3 的用户
    内存
    82.28MB
    击败 38.51%使用 Python3 的用户

    class TrieNode:
        def __init__(self):
            # 每个节点有26个可能的子节点, 对应26个英文字母
            self.children = [None] * 26
            # 标记这个节点是否是当前单词的最后一个字母
            self.isLast = False
    
    class WordDictionary:
        def __init__(self):
            # 初始化时创建根节点
            self.li = TrieNode()
    
        def addWord(self, word: str) -> None:
            # 从根节点开始
            node = self.li
            # 遍历单词中的每个字母
            for w in word:
                # 计算字母对应的索引
                c = ord(w) - ord('a')
                # 如果相应的子节点不存在
                if not node.children[c]:
                    # 创建新的子节点
                    node.children[c] = TrieNode()
                # 移动到子节点, 继续处理下一个字母
                node = node.children[c]
            # 标记单词的最后一个字母
            node.isLast = True
    
        def search(self, word: str) -> bool:
            def dfs(index:int, node: TrieNode) -> bool:
                # 如果已经检查完单词的所有字母
                if index == len(word):
                    # 如果是单词的结尾, 则返回 True
                    return node.isLast
                # 获取当前字母
                w = word[index]
                # 如果当前字母不是通配符
                if w != '.':
                    # 计算字母的索引
                    c = ord(w) - ord('a')
                    # 获取相应的子节点
                    child = node.children[c]
                    # 如果子节点存在, 递归搜索下一个字母
                    if child is not None and dfs(index+1, child):
                        return True
                # 如果是通配符
                else:
                    # 遍历所有可能的子节点
                    for nc in node.children:
                        # 如果子节点存在, 递归搜索下一个字母
                        if nc is not None and dfs(index+1,nc):
                            # 返回True, 如果找到匹配的路径
                            return True
                # 如果没有找到匹配的路径, 返回 False
                return False
            # 从根节点开始深度优先搜索
            return dfs(0, self.li)
    
    
    # Your WordDictionary object will be instantiated and called as such:
    # obj = WordDictionary()
    # obj.addWord(word)
    # param_2 = obj.search(word)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
  • 相关阅读:
    硬件接口和软件接口
    EasyRecovery2023互盾免费数据恢复软件下载功能介绍
    NoSQL之Redis配置与优化
    KubeSphere 社区双周报 | 功能亮点抢“鲜”看 | 2022-09-16
    【C++多线程那些事儿】多线程的执行顺序如你预期吗?
    39.SSH远程终端连接工具
    Python中的matplotlib与Pygal的安装、使用与实例
    STC 51单片机47——外部中断控制流水灯
    京东数据平台:2023年9月京东净水器行业品牌销售排行榜!
    为什么使用ray_tune对自己改进的yolov8模型调优时
  • 原文地址:https://blog.csdn.net/Ashiu/article/details/134258564