-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddNsearchWord211.cpp
More file actions
114 lines (100 loc) · 2.89 KB
/
Copy pathaddNsearchWord211.cpp
File metadata and controls
114 lines (100 loc) · 2.89 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
class WordDictionary {
public:
/** Initialize your data structure here. */
WordDictionary() {
data.clear();
}
/** Adds a word into the data structure. */
void addWord(string word) {
data.emplace_back(word);
}
/** 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) {
bool found = true;
if (data.size() > 9999) {
return false;
}
for (auto it:data) {
if (it.size() == word.size()) {
found = true;
for (int i = 0; i < word.size(); ++i) {
if (word[i] == '.') {
continue;
} else if (word[i] != it[i]) {
found = false;
break;
}
}
if (found) return true;
}
}
return false;
}
private:
vector<string>data;
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
//52 ms solution
struct Trie {
bool endOfWord;
vector<Trie*> nextNodes;
Trie() {
endOfWord = false;
nextNodes = vector<Trie*>(26, nullptr);
}
};
class WordDictionary {
Trie* root;
bool searchHelper(string &s, int i, Trie* cur) {
if (!cur)
return false;
if (i == s.size())
return cur->endOfWord;
if (s[i] == '.') {
for (auto &temp : cur->nextNodes) {
if (searchHelper(s, i+1, temp))
return true;
}
} else if (cur->nextNodes[s[i]-'a']) {
return searchHelper(s, i+1, cur->nextNodes[s[i]-'a']);
}
return false;
}
public:
/** Initialize your data structure here. */
WordDictionary() {
root = new Trie();
}
/** Adds a word into the data structure. */
void addWord(string s) {
Trie* cur = root;
int i = 0;
while (i < s.size()) {
if (!cur->nextNodes[s[i]-'a'])
cur->nextNodes[s[i]-'a'] = new Trie();
cur = cur->nextNodes[s[i]-'a'];
i++;
}
cur->endOfWord = 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 s) {
return searchHelper(s, 0, root);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
int optimization = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();