Implement Trie(LintCode)

Implement Trie

Implement a trie with insert, search, and startsWith methods.

樣例
 
注意

You may assume that all inputs are consist of lowercase letters a-z.ide

 

百度了一下,瞭解了字典樹是啥,而後看了下實現的代碼,而後本身寫仍是不難的(是啊,知道答案固然不會以爲難)。this

 

字典樹

又稱單詞查找樹, 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 }
View Code
相關文章
相關標籤/搜索