Problem: Implement Trie (Prefix Tree)
Implement a trie with insert, search, and startsWith methods
Note:
You may assume that all inputs are consist of lowercase letters a-z.
class TrieNode {
public:
TrieNode *child[26];
int countPrefix;
bool isEnd;
TrieNode() {
countPrefix = 0;
isEnd =false;
for(int i=0;i<26;i++)
child[i]=NULL;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode *head = root;
int sl=word.length();
for(int i=0;i<sl;i++)
{
int index = word[i] - 'a';
if(head->child[index]==NULL)
head->child[index] = new TrieNode();
head->child[index]->countPrefix++;
head = head->child[index];
}
head->isEnd=true;
}
bool search(string word) {
TrieNode *head = getLastNode(word);
if(head==NULL) return false;
return head->isEnd;
}
bool startsWith(string prefix) {
TrieNode *head = getLastNode(prefix);
if(head==NULL) return false;
if(head->countPrefix) return true;
return false;
}
TrieNode* getLastNode(string s)
{
TrieNode *head = root;
int sl=s.length();
for(int i=0;i<sl;i++)
{
int index = s[i]-'a';
if(head->child[index]==NULL)
return NULL;
head = head->child[index];
}
return head;
}
private:
TrieNode* root;
};
No comments:
Post a Comment