208. 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: bool isWord; vector<TrieNode* >child; TrieNode():isWord(false),child(vector<TrieNode* >(26,nullptr)){}; }; class Trie { public: /** Initialize your data structure here. */ Trie(){ root=new TrieNode(); } /** Inserts a word into the trie. */ void insert(string word) { TrieNode* temp=root; for(int i=0;i<word.length();i++){ int c=word[i]-'a'; if(temp->child[c]==NULL)temp->child[c]=new TrieNode(); temp=temp->child[c]; } temp->isWord=true; } /** Returns if the word is in the trie. */ bool search(string word) { TrieNode* temp=root; for(int i=0;i<word.length();i++){ int c=word[i]-'a'; if(temp->child[c]==NULL)return false; temp=temp->child[c]; } return temp->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { TrieNode* temp=root; for(int i=0;i<prefix.length();i++){ int c=prefix[i]-'a'; if(temp->child[c]==NULL)return false; temp=temp->child[c]; } return true; } private: TrieNode* root; }; /** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * bool param_2 = obj.search(word); * bool param_3 = obj.startsWith(prefix); */