Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

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

 

由于用的是 26位字母的array, 所以在trieNode 上甚至不用存val。

 1 class TrieNode {
 2     // Initialize your data structure here.
 3     Boolean isWord;
 4     TrieNode[] children;
 5     
 6     public TrieNode(){
 7         this.isWord = false;
 8         children = new TrieNode[26];
 9     }
10 }
11 
12 public class Trie {
13     private TrieNode root;
14 
15     public Trie() {
16         root = new TrieNode();
17     }
18 
19     // Inserts a word into the trie.
20     public void insert(String word) {
21         TrieNode cur = root;
22         for(int i = 0; i < word.length(); i ++){
23             Character c = word.charAt(i);
24             if(cur.children[c - 'a'] == null){
25                 TrieNode tmp = new TrieNode();
26                 cur.children[c - 'a'] = tmp;
27             }
28             cur = cur.children[c - 'a'];
29         }
30         cur.isWord = true;
31     }
32     
33     private TrieNode findNode(String word){
34         TrieNode cur = root;
35         for(int i = 0; i < word.length(); i ++){
36             Character c = word.charAt(i);
37             if(cur.children[c - 'a'] == null){
38                 return null;
39             }
40             cur = cur.children[c - 'a'];
41         }
42         return cur;
43     }
44     
45     // Returns if the word is in the trie.
46     public boolean search(String word) {
47         TrieNode end = findNode(word);
48         return end != null && end.isWord;
49     }
50 
51     // Returns if there is any word in the trie
52     // that starts with the given prefix.
53     public boolean startsWith(String prefix) {
54         return findNode(prefix) != null;
55     }
56 }
57 
58 // Your Trie object will be instantiated and called as such:
59 // Trie trie = new Trie();
60 // trie.insert("somestring");
61 // trie.search("key");

 

posted on 2015-05-08 12:44  Step-BY-Step  阅读(211)  评论(0编辑  收藏  举报

导航