#include <iostream>
#include <string.h>
using namespace std;
class WordDictionary {
public:
struct node {
bool end;
node *child[26];
node() {
end = false;
memset(child, 0, sizeof(child));
}
};
WordDictionary() {
root = NULL;
}
// Adds a word into the data structure.
void addWord(string word) {
if (!root) {
root = new node();
}
int counter = 0;
node *current = root;
while (counter != word.length()) {
if (!current->child[word[counter] - 'a']) {
current->child[word[counter] - 'a'] = new node();
}
current = current->child[word[counter] - 'a'];
counter++;
}
current->end = true;
}
bool search(node *start, string word) {
if (!start) {
return false;
}
if (word.length() == 0 && start->end) {
return true;
}
if (word.length() == 0 && !start->end) {
return false;
}
if (word[0] == '.') {
for (int i = 0; i < 26; i++) {
if (start->child[i]) {
if (search(start->child[i], word.c_str() + 1)) {
return true;
}
}
}
return false;
}
if (start->child[word[0] - 'a']) {
return search(start->child[word[0] - 'a'], word.c_str() + 1);
}
return false;
}
// 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) {
return search(root, word);
}
private:
node *root;
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
int main(int argc, const char * argv[]) {
WordDictionary wordDictionary;
wordDictionary.addWord("aa");
wordDictionary.addWord("wef");
cout << wordDictionary.search(".") << endl;
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
leetcode-211-Add and Search Word - Data structure design
最新推荐文章于 2022-11-01 19:14:02 发布