LeetCode OJ:Implement Trie (Prefix Tree)(实现一个字典树(前缀树))
2016-01-13 16:30
513 查看
Implement a trie with
实现字典树,前面好像有道题做过类似的东西,代码如下:
insert,
search, and
startsWithmethods.
实现字典树,前面好像有道题做过类似的东西,代码如下:
class TrieNode { public: // Initialize your data structure here. TrieNode():isLeaf(false) { for(auto & t : dic){ t = NULL; } } TrieNode * dic[26]; bool isLeaf; }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string word) { TrieNode * p = root; for(int i = 0; i < word.size(); ++i){ int index = word[i] - 'a'; if(p->dic[index] == NULL) p->dic[index] = new TrieNode(); p = p->dic[index]; } p->isLeaf = true; } // Returns if the word is in the trie. bool search(string word) { TrieNode * p = root; for(int i = 0; i < word.size(); ++i){ int index = word[i] - 'a'; if(p->dic[index] == NULL) return false; p = p->dic[index]; } return p->isLeaf; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { TrieNode * p = root; for(int i = 0; i < prefix.size(); ++i){ int index = prefix[i] - 'a'; if(p->dic[index] == NULL) return false; p = p->dic[index]; } return true; } private: TrieNode* root; }; // Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- jquery悬浮提示框完整实例
- 编辑表格@tableView实现分区,索引
- js和jquery实现监听键盘事件示例代码
- Spring Security介绍
- Win10 Mobile用户怎么退出预览版升级正式版?
- Practice In Python UT & Coverage
- Android 蓝牙打印机Service Intent must be explicit
- Android百度定位SDK,返回error code:162 latitude:4.9E-32
- 错误输出
- NtRights
- 伺服电机原理
- 线程结束资源释放
- iOS开发之键盘类型UIKeyboardType
- 从页面上获取多选框的值进数据库查询
- Unity 使用自定义资源(.asset)配置数据
- ESP8266学习笔记1:怎样在安信可全功能測试板上实现ESP-01的编译下载和调试
- php读取大文件
- Solving “Dynamic Web Module 3.0 requires Java 1.6 or newer” in Maven Projects
- 20160113006 asp.net实现ftp上传代码(解决大文件上传问题)
- shell 循环