Trie树(字典树)的实现
来源:互联网 发布:php上传文件源码 编辑:程序博客网 时间:2024/05/16 14:04
Lintcode 442上实现Trie树
http://www.lintcode.com/zh-cn/problem/implement-trie/
class TrieNode{public: TrieNode() { for(int i = 0; i < 26; i++) { children[i] = nullptr; isEnd = false; } }public: char data; TrieNode * children[26]; bool isEnd;};class Trie {public: Trie() { // do intialization if necessary root = new TrieNode(); } /* * @param word: a word * @return: nothing */ void insert(string &word) { // write your code here int wordLen = word.length(); if(wordLen > 0) { TrieNode * cur = root; for(int index = 0; index < wordLen; index++) { int childIndex = word[index] - 'a'; if(cur->children[childIndex] == nullptr) { cur->children[childIndex] = new TrieNode(); cur->children[childIndex]->data = word[index]; } cur = cur->children[childIndex]; } cur->isEnd = true; } } /* * @param word: A string * @return: if the word is in the trie. */ bool search(string &word) { // write your code here int wordLen = word.length(); if(wordLen > 0) { TrieNode * cur = root; for(int index = 0; index < wordLen; index++) { int childIndex = word[index] - 'a'; if(cur->children[childIndex] == nullptr) { return false; } cur = cur->children[childIndex]; } if(cur->isEnd) { return true; } } return false; } /* * @param prefix: A string * @return: if there is any word in the trie that starts with the given prefix. */ bool startsWith(string &prefix) { // write your code here int wordLen = prefix.length(); if(wordLen > 0) { TrieNode * cur = root; for(int index = 0; index < wordLen; index++) { int childIndex = prefix[index] - 'a'; if(cur->children[childIndex] == nullptr) { return false; } cur = cur->children[childIndex]; } return true; } return false; }private: TrieNode * root;};
阅读全文
0 0
- Trie树(字典树)的实现
- Trie树(字典树)的实现
- 字典树(Trie)的java实现
- Trie(字典树)的Java实现
- 字典树 Trie 的实现
- trie字典树实现
- trie(字典树)的双数组实现
- 一个Trie字典树的简单实现
- 实现字典树Trie的基本操作
- 字典树(Trie)的简单实现
- 7. implement-trie(实现trie字典树)
- Trie树|字典树的简介及实现(转)
- 字典树(Trie树)的C程序实现代码
- Trie树|字典树的简介及实现(转)
- Trie树|字典树的简介及实现(转)
- Trie树(字典树)的原理及其实现
- Trie树(字典树)的C++实现
- Trie树|字典树的简介及实现(转)
- echo 写设备节点后无限循环调用linux驱动下的write函数
- c语言经典例题5
- 欢迎使用CSDN-markdown编辑器
- 栈内存和堆内存案例
- CSS3-转换之translate
- Trie树(字典树)的实现
- Android 仿微信实现语音聊天功能
- 使用MQTTlens和Mosquitto在WIN7上完成发布和订阅
- C#删除文件夹
- Hibernate 框架的搭建及简单介绍
- 微信开放平台 redirect_uri参数错误
- iOS一行代码移除子视图,或者layer。iOS获取近八天日期数组
- windows下批处理删除文件及注册表项
- [ Pollard_rho ] BZOJ4802