-
Notifications
You must be signed in to change notification settings - Fork 0
/
473. 单词的添加与查找.cpp
80 lines (75 loc) · 2.11 KB
/
473. 单词的添加与查找.cpp
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class WordDictionary {
public:
/*
* @param word: Adds a word into the data structure.
* @return: nothing
*/
class TrieNode{
public:
#define MAX 256
int count;
class TrieNode *symbol[MAX];
TrieNode(){
this->count = 0;
for(int i=0; i<MAX; i++)
symbol[i] = NULL;
}
};
class TrieNode *root;
WordDictionary(){
root = new TrieNode();
}
void addWord(string &word) {
// write your code here
if(word.size()==0)
return;
class TrieNode *p = root;
for(int i=0; i<word.size(); i++)
{
int idx = word[i];
if(p->symbol[idx] == NULL)
p->symbol[idx] = new TrieNode();
p = p->symbol[idx];
}
p->count++;
}
bool search_dfs(string word, class TrieNode *root)
{
if(word.size()==0 && root->count>0)
return true;
for(int i=0; i<word.size(); i++)
{
if(word[i] == '.')
{
for(int j=0; j<MAX; j++)
{
if(root->symbol[j] != NULL && search_dfs(word.substr(i+1), root->symbol[j]))
return true;
}
return false;
}
else
{
int idx = word[i];
if(root->symbol[idx] == NULL)
return false;
root = root->symbol[idx];
}
}
if(root->count > 0)
return true;
return false;
}
/*
* @param word: A word could contain the dot character '.' to represent any one letter.
* @return: if the word is in the data structure.
*/
bool search(string &word) {
// write your code here
return search_dfs(word, root);
}
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");