[leetcode刷题笔记]Implement Trie (Prefix Tree)
2015-07-14 19:53
295 查看
题目链接
一A,开森~
ac代码:
一A,开森~
ac代码:
class TrieNode { // Initialize your data structure here. char content; boolean isWord; int count; LinkedList<TrieNode> childList; public TrieNode(char c) { content = c; isWord = false; count = 0; childList = new LinkedList<TrieNode>(); } public TrieNode() { content = ' '; isWord = false; count = 0; childList = new LinkedList<TrieNode>(); } public TrieNode findChildC(char c){ if(childList != null){ for(TrieNode eachChild:childList){ if(eachChild.content == c) return eachChild; } } return null; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { //if already has this word if(search(word) == true) return; TrieNode current = root; for(int i = 0;i < word.length();i++){ TrieNode child = current.findChildC(word.charAt(i)); if(child == null){ TrieNode temp = new TrieNode(word.charAt(i)); current.childList.add(temp); current = temp; }else{ current = child; } current.count++; } current.isWord = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode current = root; for(int i = 0;i < word.length();i++){ TrieNode child = current.findChildC(word.charAt(i)); if(child == null) return false; else{ current = child; continue; } } if(current.isWord) return true; return false; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode current = root; for(int i = 0;i < prefix.length();i++){ TrieNode child = current.findChildC(prefix.charAt(i)); if(child == null) return false; else{ current = child; continue; } } return true; } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- MarkDown的使用、JAVA环境变量的配置、JAVA基础
- 接触式IC卡
- 汉诺塔问题
- Python Idle 无法显示行号(上)
- web项目部署到linux服务器出现的问题
- 使用蒲公英来做iOS测试应用的分发
- UVa 10285 - Longest Run on a Snowboard
- 无限分类树操作
- espcms内容页相册调用代码
- c++对象模型-the semantics of constr ad97 uctors
- 【SeekBar】Android 自定义漂亮的SeekBar样式
- debian 8下修改默认编辑器
- C8_指针练习
- LeetCode题解——Generate Parentheses
- 大楼扔鸡蛋问题(动态规划)
- 【Spark】SparkContext源码解读
- 【Spark】Spark的Shuffle机制
- [转载] 最全最强解析:支付宝系统架构内部剖析(架构图)
- C8_指针
- Class文件结构