forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
66 lines (58 loc) · 1.44 KB
/
Solution.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
class trie {
public:
vector<trie*> children;
bool is_end;
trie() {
children = vector<trie*>(26, nullptr);
is_end = false;
}
void insert(const string& word) {
trie* cur = this;
for (char c : word) {
c -= 'a';
if (cur->children[c] == nullptr) {
cur->children[c] = new trie;
}
cur = cur->children[c];
}
cur->is_end = true;
}
};
class WordDictionary {
private:
trie* root;
public:
WordDictionary() : root(new trie) {}
void addWord(string word) {
root->insert(word);
}
bool search(string word) {
return dfs(word, 0, root);
}
private:
bool dfs(const string& word, int i, trie* cur) {
if (i == word.size()) {
return cur->is_end;
}
char c = word[i];
if (c != '.') {
trie* child = cur->children[c - 'a'];
if (child != nullptr && dfs(word, i + 1, child)) {
return true;
}
} else {
for (trie* child : cur->children) {
if (child != nullptr && dfs(word, i + 1, child)) {
return true;
}
}
}
return false;
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/