forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add_and_Search_Word_Data_structure_design.cpp
69 lines (62 loc) · 2.01 KB
/
Add_and_Search_Word_Data_structure_design.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
class WordDictionary {
public:
WordDictionary(): root(new Node()) {
}
// Adds a word into the data structure.
void addWord(string word) {
int len = word.length();
Node* pCrawl = root;
for(int i = 0; i < len; ++i) {
int indx = (int) (word[i] - 'a');
if(!pCrawl->children[indx]) {
pCrawl->children[indx] = new Node();
}
pCrawl = pCrawl->children[indx];
}
pCrawl->mark = 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) {
Node *pCrawl = root;
return searchUtil(word, pCrawl);
}
private:
const static int SIZE = 30;
struct Node {
bool mark;
Node *children[SIZE];
Node(): mark(false) {
for(int i = 0; i < SIZE; ++i) {
children[i] = nullptr;
}
}
};
Node *root = nullptr;
bool searchUtil(string word, Node* pCrawl) {
int len = word.length();
for(int i = 0; i < len; ++i) {
int indx = (int) (word[i] - 'a');
if(word[i] == '.') {
bool found = false;
for(int k = 0; k < SIZE; ++k) {
if(pCrawl->children[k]) {
if(searchUtil(word.substr(i + 1), pCrawl->children[k])) {
return true;
}
}
}
return false;
}
if(!pCrawl->children[indx]) {
return false;
}
pCrawl = pCrawl->children[indx];
}
return pCrawl->mark == true;
}
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");