实现一个 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; } };