208. Implement Trie (Prefix Tree)

标准trie的结构是

1 class TrieNode {
2    TrieNode[] child;
3    char curChar;
4    HashSet<Integer> hashset;
5    int freq;             
6 }

但是这题里面我们不需要freq也不需要hashset,但是为了表示当前节点是不是作为过一个词的结尾,我们设置一个boolean isLeaf。

这么做的理由是,考虑以下两种情况:

1. 假如插入ab,但是要搜索a,就应该返回false,搜prefix就应该返回true

2. 插入了ab,abc, 搜索ab就应该返回true, 搜prefix ab也应该返回true

所以我们要记录一下是不是结尾

 

 1 class TrieNode {
 2     // Initialize your data structure here.
 3     public TrieNode[] children;
 4     public char curChar;
 5     public boolean isLeaf;
 6     
 7     public TrieNode() {
 8         children = new TrieNode[26];
 9         isLeaf = false;
10     }
11 }
12 
13 public class Trie {
14     private TrieNode root;
15 
16     public Trie() {
17         root = new TrieNode();
18     }
19 
20     // Inserts a word into the trie.
21     public void insert(String word) {
22         int len = word.length();
23         if(len == 0) {
24             return;
25         }
26         TrieNode curNode = root;
27         for(int i = 0; i < len; i++) {
28             char cur = word.charAt(i);
29             int index = cur - 'a';
30             if(curNode.children[index] == null) {
31                 curNode.children[index] = new TrieNode();
32                 curNode.children[index].curChar = cur;
33             }
34             curNode = curNode.children[index];
35         }
36         curNode.isLeaf = true;
37     }
38 
39     // Returns if the word is in the trie.
40     public boolean search(String word) {
41         if(word.length() == 0) {
42             return true;
43         }
44         TrieNode curNode = root;
45         for(int i = 0; i < word.length(); i++) {
46             char cur = word.charAt(i);
47             int index = cur - 'a';
48             if(curNode.children[index] == null) {
49                 return false;
50             }
51             curNode = curNode.children[index];
52         }
53         return curNode.isLeaf;
54     }
55     
56     // Returns if there is any word in the trie
57     // that starts with the given prefix.
58     public boolean startsWith(String prefix) {
59         if(prefix.length() == 0) {
60             return true;
61         }
62         TrieNode curNode = root;
63         for(int i = 0; i < prefix.length(); i++) {
64             char cur = prefix.charAt(i);
65             int index = cur - 'a';
66             if(curNode.children[index] == null) {
67                 return false;
68             }
69             if(curNode.children[index].curChar != cur) {
70                 return false;
71             }
72             curNode = curNode.children[index];
73         }
74         return true;
75     }
76 }
77 
78 // Your Trie object will be instantiated and called as such:
79 // Trie trie = new Trie();
80 // trie.insert("somestring");
81 // trie.search("key");

 

posted @ 2016-07-22 04:32  warmland  阅读(405)  评论(0编辑  收藏  举报