-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy path211. Add and Search Word - Data structure design.cpp
77 lines (67 loc) · 1.8 KB
/
211. 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
70
71
72
73
74
75
76
77
// Solution 1. Hash Table, 62ms, 100%.
class WordDictionary {
public:
WordDictionary() {}
void addWord(string word) {
words[word.size()].push_back(word);
}
bool search(string word) {
for(auto s: words[word.size()]) if(isEqual(s, word)) return true;
return false;
}
private:
unordered_map<int, vector<string>>words;
bool isEqual(string a, string b){
for(int i = 0; i < a.size(); i++){
if(b[i] == '.') continue;
if(a[i] != b[i]) return false;
}
return true;
}
};
// Solution 2. Trie, 88ms.
struct TrieNode{
bool isKey;
TrieNode* next[26];
TrieNode():isKey(false){
memset(next, NULL, sizeof(next));
}
};
class WordDictionary {
public:
WordDictionary() {
root = new TrieNode();
}
void addWord(string word) {
TrieNode* node = root;
for(auto c: word){
if(!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->isKey = true;
}
bool search(string word) {
return helper(word, root);
}
private:
TrieNode* root;
bool helper(string word, TrieNode* node){
for(int i = 0; i < word.size(); i++){
char c = word[i];
if(c != '.'){
if(!node->next[c - 'a']) return false;
node = node->next[c - 'a'];
}
else{
bool found = false;
int j = 0;
for(; j < 26; j++){
if(node->next[j]) found |= helper(word.substr(i + 1), node->next[j]);
if(found) return true;
}
if(j == 26) return false;
}
}
return node->isKey;
}
};