#include <vector>
#include <string>
#include <iostream>
using namespace std;
/* This is a trie implemention */
class TrieNode {
public:
bool isWord;
vector<TrieNode*> child;
TrieNode() : isWord(false) {child.assign(26, NULL);}
};
class Trie {
private:
bool searchWord(string& word, TrieNode* p, int index) {
if(p == NULL) return false;
if(idx == word.size()) return p->isWord;
if(word[index] == '.') { // skip it!
for(auto q : p->child) {
if(searchWord(word, q, index+1)) return true;
}
return false;
} else {
return searchWord(word, p->child[word[index] - 'a'], index + 1);
}
}
public:
Trie() {
root = new TrieNode();
}
/* adds a word into the data structure. */
void addWord(string word) {
TrieNode* p = root;
for(auto c : word) {
int index = c - 'a';
if(p->child[index] == NULL) {
p->child[index] = new TrieNode();
}
p = p->child[index];
}
p->isWord = true;
}
/*
Returns if the word is in the data structure. A word cound
contain the dot character '.' to represent any one letter.
*/
bool search(string word) {
return searchWord(word, root, 0);
}
};
LeetCode 211. Add and Search Word - Data structure design
最新推荐文章于 2019-01-23 13:54:00 发布