實現一個 Trie,包含 insert, search, 和 startsWith 這三個方法。spa
insert("lintcode")
search("code") // return false
startsWith("lint") // return true
startsWith("linterror") // return false
insert("linterror")
search("lintcode) // return true
startsWith("linterror") // return truecode
思路:
樹節點採用哈希表來映射字母和子節點的關係。
//定義樹節點 class TrieNode{ public: unordered_map<char, TrieNode*> ChildNode; bool isLeaf; TrieNode(){ isLeaf = false;//肯定一個字符串是否結束 } }; class Trie { public: TrieNode * root; Trie() { // do intialization if necessary root = new TrieNode(); } /* * @param word: a word * @return: nothing */ void insert(string &word) { // write your code here TrieNode *cur = root; for(int i=0; i<word.size(); i++){ if(cur->ChildNode.find(word[i]) == cur->ChildNode.end()){ cur->ChildNode[word[i]] = new TrieNode(); } cur = cur->ChildNode[word[i]]; } cur->isLeaf = true; } /* * @param word: A string * @return: if the word is in the trie. */ bool search(string &word) { // write your code here TrieNode *cur = root; for(int i=0; i<word.size(); i++){ if(cur->ChildNode.find(word[i]) == cur->ChildNode.end()){ return false; } cur = cur->ChildNode[word[i]]; } if(cur->isLeaf) return true; else return false; } /* * @param prefix: A string * @return: if there is any word in the trie that starts with the given prefix. */ bool startsWith(string &prefix) { // write your code here TrieNode *cur = root; for(int i=0; i<prefix.size(); i++){ if(cur->ChildNode.find(prefix[i]) == cur->ChildNode.end()){ return false; } cur = cur->ChildNode[prefix[i]]; } return true; } };