Note: You may assume that all inputs are consist of lowercase letters a-z. All inputs are guaranteed to be non-empty strings.
Solution:
Trie is an important data structure that frequently appeared in interviews. To design a TrieNode, we need a word collection child[26], which is from a-z, and a boolean value isWord that denotes whether this node is a word or not.
classTrie { public: /** Initialize your data structure here. */ TrieNode* root; Trie() { root= new TrieNode(); } /** Inserts a word into the trie. */ voidinsert(string word){ TrieNode* p= root; for(auto a: word){ int i= a-'a'; if(!p->child[i]) p->child[i]= new TrieNode(); p= p->child[i]; } p->isWord= true; //!!!!!!!!!!!!!! important!!!! } /** Returns if the word is in the trie. */ boolsearch(string key){ TrieNode* p= root; for(auto c: key){ int i= c- 'a'; if(!p->child[i]) returnfalse; p= p->child[i]; } return p->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ TrieNode* p= root; for(auto c: prefix){ int i= c- 'a'; if(!p->child[i]) returnfalse; p= p->child[i]; } returntrue; } };
/** * 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); */
Insertion: time complexity: $O(m)$, m is key length space complexity: $O(m)$, m is key length
Search: time complexity: $O(m)$, m is key length space complexity: $O(1)$
Search prefix: time complexity: $O(m)$, m is key length space complexity: $O(1)