字典树
字典树,又叫Trie树,也称前缀树。典型应用是用于统计、排序和保存大量的字符串,经常被搜索引擎系统用于文本词频统计。优点:利用公共前缀来减少查询时间,最大限度地减少查询比较的次数。
struct TrieNode{ char c; bool isLeaf; TrieNode* children[26]; TrieNode(){ c=0; isLeaf=false; memset(children,NULL,sizeof(TrieNode*)*26); } TrieNode(char var){ c=var; isLeaf=false; memset(children,NULL,sizeof(TrieNode*)*26); } }; class Trie { private: TrieNode* root; public: /** Initialize your data structure here. */ Trie() { root=new TrieNode; } /** Inserts a word into the trie. */ void insert(string word) { if (word.empty()) return; TrieNode* p=root; for (int i=0;i<word.size();i++){ char var=word[i]; if (!p->children[var-'a']){ p->children[var-'a']=new TrieNode(word[i]); } p=p->children[var-'a']; } p->isLeaf=true; } /** Returns if the word is in the trie. */ bool search(string word) { if (word.empty()) return true; TrieNode* p=root; for (int i=0;i<word.size();i++){ char var=word[i]; if (p->children[var-'a']){ p=p->children[var-'a']; } else return false; } if (p->isLeaf) return true; else return false; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { if (prefix.empty()) return true; TrieNode* p=root; for (int i=0;i<prefix.size();i++){ char var=prefix[i]; if (p->children[var-'a']){ p=p->children[var-'a']; } else return false; } return true; } void freeTrieNode(TrieNode* root){ if (NULL==root) return; TrieNode* p=root; for (int i=0;i<26;i++){ if (p->children[i]) freeTrieNode(p->children[i]); } free(p); } ~Trie(){ freeTrieNode(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); */
浙公网安备 33010602011771号