Implement Trie（LintCode）

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

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

字典树

 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

posted @ 2015-12-06 23:19  -.-|  阅读(145)  评论(0编辑  收藏  举报