211. Add and Search Word - Data structure design

本文详细介绍了如何设计并实现一个名为WordDictionary的数据结构,该结构支持addWord和search两种操作。addWord用于添加单词,而search可以精确搜索单词或使用正则表达式进行模糊匹配。文章提供了两种解决方案,一种基于列表的简单实现,另一种使用了更高效的字典树(Trie)结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

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

Note:
You may assume that all words are consist of lowercase letters a-z.

Accepted
95,401
Submissions
341,383

Solution1:(TLE)

class WordDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.l = []

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: void
        """
        self.l.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
        """
        def judge(a,b):
            if len(a)!=len(b):
                return False
            i = 0
            while i<len(word):
                if a[i]==b[i]:
                    i += 1
                    continue
                if b[i]=='.':
                    i += 1
                    continue
                return False
            return True
        for w in self.l:
            if judge(w,word):
                return True
        return False

# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

12 / 13 test cases passed.

Solution2:

import collections
class Node:
    def __init__(self):
        self.children = collections.defaultdict(Node)
        self.isword = False
        
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
        """
        current = self.root
        for w in word:
            current = current.children[w]
        current.isword = True
        return 

    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.match(word,0,self.root)
    
    def match(self,word,index,root):
        if root==None:
            return False
        if index== len(word):
            return root.isword
        if word[index] != '.':
            return root != None and self.match(word,index+1,root.children.get(word[index]))
        else:
            for child in root.children.values():
                if self.match(word,index+1,child):
                    return True
        return False

# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

转载于:https://www.cnblogs.com/bernieloveslife/p/10051059.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值