-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path211.cpp
91 lines (82 loc) · 2.33 KB
/
211.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// sometimesBetter.cpp
class WordDictionary {
unordered_map<int, unordered_set<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;
}
public:
/** Initialize your data structure here. */
WordDictionary() {}
/** Adds a word into the data structure. */
void addWord(string word) { words[word.size()].insert(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) {
if (words[word.size()].find(word) != words[word.size()].end())
return true;
for (auto s : words[word.size()]) {
if (isEqual(s, word))
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);
*/
// trie.cpp
class WordDictionary2 {
struct trie {
trie() : isWord(false) { memset(this->children, 0, sizeof(children)); }
bool isWord;
trie *children[26];
} root;
public:
/** Initialize your data structure here. */
WordDictionary2() {}
/** Adds a word into the data structure. */
void addWord(string word) {
trie *p = &root;
for (auto ch : word) {
int offset = ch - 'a';
if (p->children[offset] == nullptr)
p->children[offset] = new trie();
p = p->children[offset];
}
p->isWord = 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) {
trie *p = &root;
return helper(word, 0, p);
}
bool helper(string &word, int index, trie *p) {
if (p == nullptr)
return false;
if (index == word.size())
return p->isWord;
if (word[index] == '.') {
for (int i = 0; i < 26; ++i)
if (helper(word, index + 1, p->children[i]))
return true;
return false;
}
return helper(word, index + 1, p->children[word[index] - 'a']);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* bool param_2 = obj.search(word);
*/