LeetCode 208. Implement Trie (Prefix Tree)(前缀树)
2016-05-04 10:11
204 查看
原题网址:https://leetcode.com/problems/implement-trie-prefix-tree/
Implement a trie with
and
Note:
You may assume that all inputs are consist of lowercase letters
方法:使用数组实现下一节点的指向。
Implement a trie with
insert,
search,
and
startsWithmethods.
Note:
You may assume that all inputs are consist of lowercase letters
a-z.
方法:使用数组实现下一节点的指向。
class TrieNode { // Initialize your data structure here. boolean isWord; TrieNode[] nexts = new TrieNode[26]; public TrieNode() { } TrieNode append(int id) { if (nexts[id] != null) return nexts[id]; nexts[id] = new TrieNode(); return nexts[id]; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { TrieNode node = root; char[] wa = word.toCharArray(); for(int i=0; i<wa.length; i++) node = node.append(wa[i]-'a'); node.isWord = true; } // Returns if the word is in the trie. public boolean search(String word) { if (word == null) return root.isWord; TrieNode node =root; char[] wa = word.toCharArray(); for(int i=0; i<wa.length; i++) { if (node.nexts[wa[i]-'a'] == null) return false; node = node.nexts[wa[i]-'a']; } return node.isWord; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { if (prefix == null) return root.isWord; TrieNode node =root; char[] pa = prefix.toCharArray(); for(int i=0; i<pa.length; i++) { if (node.nexts[pa[i]-'a'] == null) return false; node = node.nexts[pa[i]-'a']; } return true; } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- java 读取properties文件
- SoapUI 设置 request data with json body
- Delphi 调用串口例子
- 数据分析的方法与技术
- MyBatis学习总结(三)——优化MyBatis配置文件中的配置
- 关于URL编码
- Android Studio HelloWord 测试程序在Android5.1真机上运行异常分析
- Android Studio HelloWord 测试程序在Android5.1真机上运行异常分析
- Android Studio HelloWord 测试程序在Android5.1真机上运行异常分析
- Android Studio HelloWord 测试程序在Android5.1真机上运行异常分析
- Android Studio HelloWord 测试程序在Android5.1真机上运行异常分析
- 控制器生命周期
- 反射代码块,自己理解
- java mongo操作
- C#(四)
- 阻止表单元素失去焦点
- GestureDetector手势识别的各个方法
- 移植u-boot到mini2440--从norflash启动
- 如何取得Spring管理的bean
- 基于OpenCL的深度学习工具:AMD MLP及其使用详解