[leetcode][trie] Implement Trie (Prefix Tree)
2015-08-18 13:56
417 查看
题目:
Implement a trie with
and
Note:
You may assume that all inputs are consist of lowercase letters
Implement a trie with
insert,
search,
and
startsWithmethods.
Note:
You may assume that all inputs are consist of lowercase letters
a-z.
class TrieNode { public: // Initialize your data structure here. TrieNode(char c = '\0') { val = c; isEnd = false; for (int i = 0; i < 26; ++i){ son[i] = NULL; } } ~TrieNode(){ for (int i = 0; i < 26; ++i){ if (son[i] != NULL) delete son[i]; } } char val; bool isEnd; TrieNode *son[26]; }; class Trie { public: Trie() { root = new TrieNode();//root不代表任何字符,剩下的每个TrieNode都代表一个字符,TrieNode的每个TrieNode指针指向下一个字符, 指针的位置代表下一个字符是什么 } ~Trie(){ delete root; } // Inserts a word into the trie. void insert(string word) { if (word.empty()) return; int n = word.size(); TrieNode *p = root; for (int i = 0; i < n; ++i){ char c = word[i]; if (p->son[c - 'a'] == NULL){ TrieNode *q = new TrieNode(c); p->son[c - 'a'] = q; } p = p->son[c - 'a']; } p->isEnd = true; } // Returns if the word is in the trie. bool search(string word) { if (word.empty()) return false; int n = word.size(); TrieNode *p = root; for (int i = 0; i < n; ++i){ char c = word[i]; if (p->son[c - 'a'] == NULL) return false; p = p->son[c - 'a']; } return p->isEnd; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) {//TODO if (prefix.empty()) return false; int n = prefix.size(); TrieNode *p = root; for (int i = 0; i < n; ++i){ char c = prefix[i]; if (p->son[c - 'a'] == NULL) return false; p = p->son[c - 'a']; } return true; } private: TrieNode* root; };
相关文章推荐
- UVA - 1336 Fixing the Great Wall 记忆化搜索
- 133. Clone Graph
- javascript Date
- iTunesConnect进行App转移2-官方说明
- spring-mvc 3.2.12及以后<mvc:resource>配置处理的变化
- comboBox1 查找其他数据
- android 16进制/10进制/2进制转换
- 二维码的生成和读取
- Effective Erlang —— 二进制型的构造和匹配
- 将多行数据变一行
- UVA-10655 Contemplation! Algebra (矩阵)
- Delphi中Interface接口的使用方法
- php表单02-表单验证
- iOS开发 -- 程序常见错误(不定时更新,适合初学)
- JS监听页面刷新或关闭事件
- 九度oj 1079
- 创建shapefile文件
- wordpress 改变站点地址
- Android Studio 快捷键 (Mac OS X 10.5+)
- 如何在abap中为ALV添加事件处理