class trieNode{
public:
trieNode *child[26];
bool isValid;
trieNode(){
for(int i = 0; i < 26; i++){
this->child[i] = NULL;
}
this->isValid = false;
}
};
class Trie {
public:
trieNode *root;
Trie() {
root = new trieNode();
}
void insert(string &word) {
int len = word.size();
trieNode *root1 = root;
for(int i = 0; i < len; i++){
if(root1->child[word[i] - 'a'] == NULL){
root1->child[word[i] - 'a'] = new trieNode();
}
root1 = root1->child[word[i] - 'a'];
}
root1->isValid = true;
return;
}
bool search(string &word) {
int len = word.size();
trieNode *root1 = root;
for(int i = 0; i < len; i++){
int idx = word[i] - 'a';
if(root1->child[idx] == NULL){
return false;
}
root1 = root1->child[idx];
}
return root1->isValid;
}
bool startsWith(string &prefix) {
int len = prefix.size();
trieNode *root1 = root;
for(int i = 0; i < len; i++){
int idx = prefix[i] - 'a';
if(root1->child[idx] == NULL){
return false;
}
root1 = root1->child[idx];
}
return true;
}
};
Comments
Post a Comment