LeetCode 题解工作台

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

请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。 实现词典类 WordDictionary : WordDictionary() 初始化词典对象 void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配 bool search…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 图·搜索

bolt

答案摘要

class Trie: def __init__(self):

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。

实现词典类 WordDictionary

  • WordDictionary() 初始化词典对象
  • void addWord(word)word 添加到数据结构中,之后可以对它进行匹配
  • bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回  falseword 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。

 

示例:

输入:
["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 由 '.' 或小写英文字母组成
  • 最多调用 104addWordsearch
lightbulb

解题思路

方法一

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
class Trie:
    def __init__(self):
        self.children = [None] * 26
        self.is_end = False


class WordDictionary:
    def __init__(self):
        self.trie = Trie()

    def addWord(self, word: str) -> None:
        node = self.trie
        for c in word:
            idx = ord(c) - ord('a')
            if node.children[idx] is None:
                node.children[idx] = Trie()
            node = node.children[idx]
        node.is_end = True

    def search(self, word: str) -> bool:
        def search(word, node):
            for i in range(len(word)):
                c = word[i]
                idx = ord(c) - ord('a')
                if c != '.' and node.children[idx] is None:
                    return False
                if c == '.':
                    for child in node.children:
                        if child is not None and search(word[i + 1 :], child):
                            return True
                    return False
                node = node.children[idx]
            return node.is_end

        return search(word, self.trie)


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

复杂度分析

指标
时间complexity depends on word length L and Trie branching; addWord is O(L), search is O(26^k * L) in worst case with k wildcards. Space complexity is O(N*L) for storing N words, considering shared prefixes in Trie nodes.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for efficient prefix storage and DFS handling of wildcards.

  • question_mark

    Check if you handle '.' correctly with recursive exploration.

  • question_mark

    Expect awareness of Trie node memory usage and early pruning for performance.

warning

常见陷阱

外企场景
  • error

    Not handling '.' correctly can miss valid matches or overcount paths.

  • error

    Failing to mark the end of words leads to false positives when searching prefixes.

  • error

    Inefficient DFS without pruning may timeout with multiple wildcard searches.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Restrict to exact matches only, removing wildcard support.

  • arrow_right_alt

    Allow arbitrary number of wildcards instead of a max of 2.

  • arrow_right_alt

    Implement with a hash map of word lengths for faster lookup without Trie.

help

常见问题

外企场景

添加与搜索单词 - 数据结构设计题解:图·搜索 | LeetCode #211 中等