Trie树是一个很有价值的中级数据结构啊,花点功夫再深究一下。
模板
Trie树的实现比较特殊,每一个节点上不是一个单独的字符,而是一个映射表:
如上图所示,每一个节点里包含当前位置字母的一个映射表,然后再有每个字母指向下一层节点。
代码
class Trie { private: bool isEnd; Trie *next[26]; public: /** Initialize your data structure here. */ Trie() { isEnd = false; memset(next, 0, sizeof(next)); } /** Inserts a word into the trie. */ void insert(string word) { Trie *node = this; for (char ch : word) { if (node->next[ch - 'a'] == NULL) { node->next[ch - 'a'] = new Trie(); } node = node->next[ch - 'a']; } node->isEnd = true; } /** Returns if the word is in the trie. */ bool search(string word) { Trie *node = this; for (char ch : word) { node = node->next[ch - 'a']; if (node == NULL) { return false; } } return node->isEnd; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { Trie *node = this; for (char ch : prefix) { node = node->next[ch - 'a']; if (node == NULL) { return false; } } return true; } }; /** * 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); */
评论
阿陈不错哦
Awesome post. I am a regular visitor of your blog and appreciate you taking the time to maintain the excellent site. I will be a frequent visitor for a long time. Manon Cornie Elwina
I wish to point out my passion for your generosity giving support to people who require help with your situation. Your special commitment to passing the solution around appears to be pretty significant and have usually made people like me to get to their aims. The important facts signifies a whole lot a person like me and a whole lot more to my fellow workers. Many thanks; from everyone of us. Frannie Prentiss Langille