一: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: // Initialize your data structure here. TrieNode() { for(int i = 0; i < 26; i++) next[i] = NULL; isString = false; } TrieNode *next[26]; bool isString; }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string s) { TrieNode *p = root; for(int i = 0; i < s.size(); i++){ if(p->next[s[i]-'a'] == NULL){ p->next[s[i]-'a'] = new TrieNode(); } p = p->next[s[i]-'a']; } p->isString = true; } // Returns if the word is in the trie. bool search(string key) { TrieNode *p = root; for(int i = 0; i < key.size(); i++){ if(p == NULL) return false; p = p->next[key[i]-'a']; } if(p == NULL || p->isString == false) return false; return true; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { TrieNode *p = root; for(int i = 0; i <= prefix.size(); i++){ if(p == NULL) return false; p = p->next[prefix[i]-'a']; } return true; } private: TrieNode* root; }; // Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key");