-
Notifications
You must be signed in to change notification settings - Fork 5
/
day-127.cpp
73 lines (58 loc) · 1.9 KB
/
day-127.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
/*
Add and Search Word - Data structure design
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing
only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
*/
// Solved using trie
class WordDictionary {
public:
/** Initialize your data structure here. */
vector<WordDictionary*> children;
bool isEndOfWord;
WordDictionary() {
children = vector<WordDictionary*>(26, NULL);
isEndOfWord = false;
}
/** Adds a word into the data structure. */
void addWord(string word) {
WordDictionary* current = this;
for (char c : word) {
if (current->children[c - 'a'] == NULL) {
current->children[c - 'a'] = new WordDictionary();
}
current = current->children[c - 'a'];
}
current->isEndOfWord = 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) {
WordDictionary* current = this;
for (int idx = 0; idx < word.length(); idx++) {
char curr = word[idx];
if (curr == '.') {
for (auto child : current->children) {
if (child && child->search(word.substr(idx + 1)))
return true;
}
return false;
}
if (current->children[curr - 'a'] == NULL) return false;
current = current->children[curr - 'a'];
}
return current && current->isEndOfWord;
}
};