[LeetCode]Implement Trie (Prefix Tree)
2015-12-06 12:36
393 查看
class TrieNode { // Initialize your data structure here. TrieNode[] child; boolean isWord; public TrieNode() { child = new TrieNode[26]; isWord = false; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { insert(word, root); } public void insert(String word, TrieNode root) { if (word.length() == 0) { root.isWord = true; return; } char ch = word.charAt(0); if (root.child[ch - 'a'] == null) { root.child[ch - 'a'] = new TrieNode(); } insert(word.substring(1), root.child[ch - 'a']); } // Returns if the word is in the trie. public boolean search(String word) { return search(word, root); } public boolean search(String word, TrieNode root) { if (word.length() == 0) { return root.isWord; } char ch = word.charAt(0); if (root.child[ch - 'a'] == null) { return false; } else { return search(word.substring(1), root.child[ch - 'a']); } } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { return startsWith(prefix, root); } public boolean startsWith(String prefix, TrieNode root) { if (prefix.length() == 0) { return true; } char ch = prefix.charAt(0); if (root.child[ch - 'a'] == null) { return false; } else { return startsWith(prefix.substring(1), root.child[ch - 'a']); } } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- 【思考一】Android程序员想做手机游戏开发
- 前后台切换会调用哪些方法
- 1096. Consecutive Factors (20)
- UEFI BIOS模式下Windows系统启动过程以及引导文件修复方法
- eclipse高效编程(一)
- 【Unix/Linux编程实践】 动手实现简单的more
- 软件开发概述
- Bete冲刺第二阶段
- G - sorry 没有北门
- 跨域问题:Access-Control-Allow-Origin
- 配置邮箱服务器
- A - 这是在网吧出的题!!
- 使用yum源安装CDH Hadoop集群
- 用Qemu模拟vexpress-a9 (一) --- 搭建Linux kernel调试环境
- 装饰设计模式(三)demo
- javaweb学习总结(七)——HttpServletResponse对象(一)
- iOS开发-多线程-GDC常用方法
- POJ 1860 Currency Exchange 解题思路
- MySql查询语句总结
- Otsu阈值化