加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:35:43 所属栏目:百科 来源:网络整理
导读:题目链接:https://leetcode-cn.com/problems/add-and-search-word-data-structure-design/ 题目描述: 设计一个支持以下两种操作的数据结构: void addWord(word)bool search(word) search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-

题目链接:https://leetcode-cn.com/problems/add-and-search-word-data-structure-design/

题目描述:

设计一个支持以下两种操作的数据结构:

void addWord(word)
bool search(word)

search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。

示例:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

说明:

你可以假设所有单词都是由小写字母 a-z 组成的。

思路:

这道题就是使用 前缀树(字典树)

先把前缀树的数据结构练习一下208. 实现 Trie (前缀树) | 题解链接

相关题型:

212. 单词搜索 II

421. 数组中两个数的最大异或值

代码:

class WordDictionary:

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

    def addWord(self,word: str) -> None:
        """
        Adds a word into the data structure.
        """
        tree = self.lookup
        for a in word:
            tree = tree.setdefault(a,{})
        tree["#"] = {}
        

    def search(self,word: str) -> bool:
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        """
        
        def helper(word,tree):
            if not word:
                if "#" in tree:
                    return True
                return False
            if word[0] == ".":
                for t in tree:
                    if helper(word[1:],tree[t]):
                        return True
            elif word[0] in tree:
                if helper(word[1:],tree[word[0]]):
                    return True
            return False
        return helper(word,self.lookup)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读