[LeetCode] Implement Trie (Prefix Tree)
2015-08-17 21:24
429 查看
You need to understand what a Trie is before writing the code :-) This link has a nice solution, whose code is rewritten below.
class TrieNode { public: bool isWord; TrieNode* children[26]; // Initialize your data structure here. TrieNode() : isWord(false) { memset(children, NULL, sizeof(TrieNode*) * 26); } }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string word) { TrieNode* run = root; for (char c : word) { if (!(run -> children[c - 'a'])) run -> children[c - 'a'] = new TrieNode(); run = run -> children[c - 'a']; } run -> isWord = true; } // Returns if the word is in the trie. bool search(string word) { TrieNode* p = query(word); return p && p -> isWord; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { return query(prefix); } private: TrieNode* root; TrieNode* query(string& s) { TrieNode* run = root; for (char c : s) { if (!(run -> children[c - 'a'])) return NULL; run = run -> children[c - 'a']; } return run; } }; // Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- uva 10556 - Biometrics(几何)
- BNU Training 2015.08.17
- 删除百度搜索结果页山寨网站排名的方法
- Swing图形界面程序—同学通讯录系统(1)
- scanf
- 小P寻宝记——好基友一起走
- 大数据算法学习笔记(七):外存算法
- uva 10335 - Ray Inside a Polygon(几何)
- qq好友列表 模拟
- 小P寻宝记——粗心的基友
- POJ 2187 Beauty Contest(凸包求最远点距离)
- Buy or Build
- ZOJ3822——概率DP——Domination
- Office导入导出组件权限配置汇总
- Linux rpmbuild命令
- 解密谷歌的大数据技术
- 接口
- POJ 1182 食物链(带权并查集)
- HDU1811-Rank of Tetris
- POJ3468 A Simple Problem with Integers 【段树】+【成段更新】