Implement Trie
Implement a trie with insert, search, and startsWith methods.
样例
注意
View Code
You may assume that all inputs are consist of lowercase letters a-z.
百度了一下,了解了字典树是啥,然后看了下实现的代码,然后自己写还是不难的(是啊,知道答案当然不会觉得难)。
-
字典树
又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
详细的可以看百度百科
1 /** 2 * Your Trie object will be instantiated and called as such: 3 * Trie trie = new Trie(); 4 * trie.insert("lintcode"); 5 * trie.search("lint"); will return false 6 * trie.startsWith("lint"); will return true 7 */ 8 class TrieNode { 9 // Initialize your data structure here. 10 char val; 11 boolean isEnd; 12 int SIZE = 26; 13 TrieNode[] children; 14 15 16 public TrieNode() { 17 children = new TrieNode[SIZE]; 18 isEnd = false; 19 } 20 public TrieNode(char val) { 21 children = new TrieNode[SIZE]; 22 this.val = val; 23 isEnd = false; 24 } 25 } 26 27 public class Solution { 28 private TrieNode root; 29 30 public Solution() { 31 root = new TrieNode(); 32 } 33 34 // Inserts a word into the trie. 35 public void insert(String word) { 36 if(word == null || word.length() == 0) return; 37 char[] cs = word.toCharArray(); 38 TrieNode p = root; 39 for(int i=0;i<cs.length;i++) { 40 int pos = cs[i] - 'a'; 41 if(p.children[pos] == null) { 42 p.children[pos] = new TrieNode(cs[i]); 43 } 44 p = p.children[pos]; 45 } 46 if(!p.isEnd) p.isEnd = true; 47 } 48 49 // Returns if the word is in the trie. 50 public boolean search(String word) { 51 if(word == null || word.length() == 0) return false; 52 char[] cs = word.toCharArray(); 53 TrieNode p = root; 54 for(int i=0;i<cs.length;i++){ 55 int pos = cs[i] - 'a'; 56 if(p.children[pos] != null) { 57 p = p.children[pos]; 58 }else return false; 59 } 60 return p.isEnd; 61 } 62 63 // Returns if there is any word in the trie 64 // that starts with the given prefix. 65 public boolean startsWith(String prefix) { 66 if(prefix == null || prefix.length() == 0) return false; 67 char[] cs = prefix.toCharArray(); 68 TrieNode p = root; 69 for(int i=0;i<cs.length;i++){ 70 int pos = cs[i] - 'a'; 71 if( p.children[pos] != null) { 72 p = p.children[pos]; 73 }else return false; 74 } 75 return true; 76 } 77 }