【LeetCode】208. Implement Trie (Prefix Tree)
2015-06-29 18:24
405 查看
Implement Trie (Prefix Tree)
Implement a trie with
Note:
You may assume that all inputs are consist of lowercase letters
一个字母代表一个子树,因此为26叉树,end标记表示是否存在以该字母为结尾的字符串。
Implement a trie with
insert,
search, and
startsWithmethods.
Note:
You may assume that all inputs are consist of lowercase letters
a-z.
一个字母代表一个子树,因此为26叉树,end标记表示是否存在以该字母为结尾的字符串。
class TrieNode { public: TrieNode* children[26]; bool end; // Initialize your data structure here. TrieNode() { for(int i = 0; i < 26; i ++) children[i] = NULL; end = false; } }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string word) { int i = 0; TrieNode* curNode = root; while(i < word.size() && curNode->children[word[i]-'a'] != NULL) { curNode = curNode->children[word[i]-'a']; i ++; } if(i == word.size()) { if(curNode->end == true) // exist return; else // insert curNode->end = true; } else { while(i < word.size()) { curNode->children[word[i]-'a'] = new TrieNode(); curNode = curNode->children[word[i]-'a']; i ++; } curNode->end = true; } } // Returns if the word is in the trie. bool search(string word) { int i = 0; TrieNode* curNode = root; while(i < word.size() && curNode->children[word[i]-'a'] != NULL) { curNode = curNode->children[word[i]-'a']; i ++; } if(i == word.size() && curNode->end == true) // curNode must be leaf return true; else return false; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { int i = 0; TrieNode* curNode = root; while(i < prefix.size() && curNode->children[prefix[i]-'a'] != NULL) { curNode = curNode->children[prefix[i]-'a']; i ++; } if(i == prefix.size()) // curNode might be left or not return true; else return false; } private: TrieNode* root; }; // Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- Netty4 之 简单搭建HTTP服务
- Dart基础-控制流程与异常处理
- dig与dns基本理论——解析和缓存
- linux_mac_配置itrem2 rz sz_bug处理
- 通过node.js保存emoji到mysql
- MyBatis+Spring+MySql
- event.srcElement || event.target
- css笔记02:选择器(标签式和类)
- Zabbix server 搭建
- hg 的 merge 和 update 的区别
- vim 配置及先过关命令
- 关于WPS-word使用多级编号级联的问题
- 2014阿里巴巴网上笔试题-文章3大标题-公共最长的字符串长度
- mysql压力测试
- J技术债务C#--防盗链
- CSS对浏览器的兼容性
- centos7下安装ifconfig 命令
- jsp A标签中文excel文件下载报404,无法下载
- Linux下的.vimrc文件
- 认识自己——恐惧的奴隶7:高中