题目链接:Add and Search Word - Data structure design
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.
For 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.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
这道题的要求是设计一种支持添加单词和查找单词的数据结构。其中查找单词时包含小写字母a-z和’.’(表示任意字母)。
存储和查找单词,可以考虑Hash表或者Trie树以提升查询效率。而由于查询时可以用’.’表示任意单个字母,因此采用Trie实现。和之前的Implement Trie (Prefix Tree)基本差不多吧。
其中插入单词,和Implement Trie (Prefix Tree)完全相同,同样是根据单词中的字母决定接下来的子树,如果不存在就建立新节点。而在查找的时候,需要对’.’进行特殊处理:需要依次遍历下面的26个子树(这里采用递归方式)。
时间复杂度:O(???)
空间复杂度:O(???)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class TrieNode
{
public:
TrieNode *next[26];
bool is_word;
// Initialize your data structure here.
TrieNode(bool b = false)
{
memset(next, 0, sizeof(next));
is_word = b;
}
};
class WordDictionary
{
TrieNode *root;
public:
WordDictionary()
{
root = new TrieNode();
}
// Adds a word into the data structure.
void addWord(string word)
{
TrieNode *p = root;
for(int i = 0; i < word.size(); ++ i)
{
if(p -> next[word[i] - 'a'] == NULL)
p -> next[word[i] - 'a'] = new TrieNode();
p = p -> next[word[i] - 'a'];
}
p -> is_word = true;
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool search(string word)
{
return search(root, word, 0);
}
private:
bool search(TrieNode *r, string &word, int b)
{
if(b == word.size())
return r != NULL && r -> is_word;
TrieNode *p = r;
for(int i = b; i < word.size() && p != NULL; ++ i)
{
if(word[i] != '.')
p = p -> next[word[i] - 'a'];
else
{
for(int j = 0; j < 26; ++ j)
if(p -> next[j] != NULL && search(p -> next[j], word, i + 1))
return true;
return false;
}
}
return p != NULL && p -> is_word;
}
};