-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path211.cpp
73 lines (66 loc) · 1.96 KB
/
211.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
#include<bits/stdc++.h>
using namespace std;
class TrieNode{
public:
TrieNode* next[26];
bool isword;
TrieNode() {
memset(next, NULL, sizeof(next));
isword = false;
}
~TrieNode() {
for (int i = 0; i < 26; ++i)
if (next[i]) delete next[i];
}
};
class WordDictionary {
TrieNode* root;
public:
/** Initialize your data structure here. */
WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode* p = root;
int n = word.size();
for (int i = 0; i < n; ++i) {
int idx = word[i] - 'a';
if (!p->next[idx]) p->next[idx] = new TrieNode();
p = p->next[idx];
}
p->isword = 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) {
TrieNode* p = find(root, word);
return p && p->isword;
}
TrieNode* find(TrieNode* p, string word) {
int n = word.size();
for(int i = 0; i < n && p; ++i) {
if (word[i] == '.') {
for (int j = 0; j < 26; ++j) {
if (p->next[j]) {
int len = word.size() - i - 1;
if (len >= 1) {
TrieNode *res = find(p->next[j], word.substr(i+1, len));
if (res && res->isword) return res;
} else if (p->next[j]->isword)
return p->next[j];
}
}
return nullptr;
} else {
p = p->next[word[i]-'a'];
}
}
return p;
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/