LeetCode 211. Design Add and Search Words Data Structure - 前缀树(Trie Tree or Prefix Tree)系列题5

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

  • WordDictionary() Initializes the object.
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.

Example:

Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]

Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True

Constraints:

  • 1 <= word.length <= 500
  • word in addWord consists lower-case English letters.
  • word in search consist of  '.' or lower-case English letters.
  • At most 50000 calls will be made to addWord and search.

也是一道前缀树(Trie Tree)的上手题,跟LeetCode 208. Implement Trie (Prefix Tree)几乎一样,唯一不同是本题查找的字符串里可能有字符 '.',表示可以匹配任意字符,因此当遇到 '. '时,需要扫描当前节点下的所有子节点(即整棵子树,可以BFS或DFS进行扫描),只要能找到一个匹配的单词即可。

class TrieNode:
    def __init__(self):
        self.end = False
        self.children = [None] * 26
        
class WordDictionary:

    def __init__(self):
        self.root = TrieNode()

    def addWord(self, word: str) -> None:
        node = self.root
        
        for c in word:
            idx = ord(c) - ord('a')
            if not node.children[idx] :
                node.children[idx] = TrieNode()
            node = node.children[idx]
        
        node.end = True

    def search(self, word: str) -> bool:
        return self.helper(self.root, word, 0)
        
    def helper(self, node, word, i):
        if not node :
            return False
        if i == len(word):
            return node.end
        
        if word[i] != '.':
            idx = ord(word[i]) - ord('a')
            return self.helper(node.children[idx], word, i + 1)
        else:
            for tmpNode in node.children:
                if not tmpNode:
                    continue
                if self.helper(tmpNode, word, i + 1):
                    return True
        
        return False

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值