Leetcode 211:添加与搜索单词 - 数据结构设计(超详细解决方案!!!)

设计一个数据结构支持搜索包含`_`通配符的字符串。解题思路包括迭代和递归版本的Trie结构实现,以及通过字典快速查询的方法。文章提供了详细解决方案并附带相关链接。
摘要由CSDN通过智能技术生成

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

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 组成的。

解题思路

由于这是一个字符串检索的问题,并且有了之前问题的基础 Leetcode 208:实现 Trie (前缀树)(超详细解决方案!!!),所以我们这里不难想到建立一个Trie结构,然后对于.的模糊匹配,通过dfs或者bfs即可解决。首先使用bfs

class Node:
    def __init__(self, isWord=False):
        self.isWord = isWord
        self.next = dict()
        
class WordDictionary:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = Node()
        
    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: void
        """
        cur = self.root
        for c in word:
            if c not in cur.next:
                cur.next[c] = Node()
            cur = cur.next[c]
            
        if not cur.isWord:
            cur.isWord = True

    def search(self, word):
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        :type word: str
        :rtype: bool
        """
        stack = [(self.root, word)]
        while stack:
            node, w = stack.pop()
            if not w:
                if node.isWord:
                    return True
            elif w[0] == '.':
                for c in node.next.values():
                    stack.append([c, w[1:]])
            elif w[0] in node.next:
                stack.append([node.next[w[0]], w[1:]])
                
        return False

迭代版本的dfs,我们只需要将stack换成queue即可。在python中,我们只需要通过pop(0)即可。

def search(self, word):
    """
    Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
    :type word: str
    :rtype: bool
    """
    stack = [(self.root, word)]
    i, word_len = 0, len(word)
    while stack:
        node, w = stack.pop(0)
        if not w:
            if node.isWord:
                return True
        elif w[0] == '.':
            for c in node.next.values():
                stack.append([c, w[1:]])
        elif w[0] in node.next:
            stack.append([node.next[w[0]], w[1:]])

    return False

dfs的递归写法。

def search(self, word):
    """
    Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
    :type word: str
    :rtype: bool
    """
    return self.dfs(self.root, word)

def dfs(self, node, word):
    if not word:
        return node.isWord

    if word[0] not in node.next:
        if word[0] == '.':
            for c in node.next.values():
                if self.dfs(c, word[1:]):
                    return True

        return False
    else:
        return self.dfs(node.next[word[0]], word[1:])

上面的写法中用了一些trick,大家可以仔细看看。这个问题最快的解法不是用Trie这个结构,而是通过字典。我们通过字典记录相同长度的单词,然后查询的时候根据单词的长度进行查询,对于包含.的单词,我们枚举所有长度一致的单词然后判断是不是存在。

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

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: void
        """
        self.root[len(word)].append(word)

    def search(self, word):
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        :type word: str
        :rtype: bool
        """
        if not word:
            return False
        
        if "." not in word:
            return word in self.root[len(word)]
        
        for v in self.root[len(word)]:
            for i, s in enumerate(word):
                if s != v[i] and s != ".":
                    break
            else:
                return True
        return False

虽然上述解法的速度很快,但是认为这不是一个优秀的解法。在python中一个建立Trie的技巧

from collections import defaultdict
    
def _trie():
    return defaultdict(_trie)

reference:

https://leetcode.com/problems/add-and-search-word-data-structure-design/discuss/59576/Tree-solutions-18-20-lines

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值