leetcode Implement Trie (Prefix Tree)
2015-08-29 14:34
381 查看
题目链接
思路:
无
思路:
无
class TrieNode { // Initialize your data structure here. TrieNode charecters[]; boolean end; public TrieNode() { charecters=new TrieNode[26]; end=false; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); root.charecters=new TrieNode[26]; } // Inserts a word into the trie. public void insert(String word) { int n=word.length(); TrieNode temp=root; for(int i=0;i<n;i++) { if(temp.charecters[word.charAt(i)-'a']==null) { temp.charecters[word.charAt(i)-'a']=new TrieNode(); } temp=temp.charecters[word.charAt(i)-'a']; } temp.end=true; } // Returns if the word is in the trie. public boolean search(String word) { int n=word.length(); TrieNode temp=root; for(int i=0;i<n;i++) { if(temp.charecters[word.charAt(i)-'a']==null) { return false; } temp=temp.charecters[word.charAt(i)-'a']; } return temp.end; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { int n=prefix.length(); TrieNode temp=root; for(int i=0;i<n;i++) { if(temp.charecters[prefix.charAt(i)-'a']==null) { return false; } temp=temp.charecters[prefix.charAt(i)-'a']; } if(temp.end) { return true; } for(int i=0;i<26;i++) { if(temp.charecters[i]!=null) { return true; } } return false; } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- Activity间数据传递与版本兼容问题
- 第二讲实例变量可见度,set/get方法,自定义初始化(代码) 及description的使用
- php中$this、static、final、const、self 等几个关键字的用法
- css去除页面点击链接、按钮触发的虚线框
- Java学习笔记(2):null 和空字符串的区别
- 3维空间旋转3维空间矩阵旋转及旋转变换
- 预测的原理及其实战(2)
- java HashMap那点事
- JavaScript 面向对象继承详解
- noip2003 麦森数 (数论,高精乘单精)
- python中range函数的使用
- Libraries: Performance vs. Native JS
- CSS选择器优先级
- jquery获取ip地址
- 弹窗实验
- 基于Apache POI 向xlsx写入数据
- 基于Apache POI 向xlsx写入数据
- Linux系统怎么查看网卡的UUID
- JavaScript学习笔记2-附录(转自w3cschool)
- 使用AFNetWorking和ReactiveCocoa对网络请求进行封装(仿煎蛋iOS)(3)