-
Notifications
You must be signed in to change notification settings - Fork 818
/
Trie.java
89 lines (78 loc) · 2.21 KB
/
Trie.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package design;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Goutham Vidya Pradhan on 7/3/2017. Implement a trie with insert, search, and
* startsWith methods.
*
* <p>Note: You may assume that all inputs are consist of lowercase letters a-z.
*/
public class Trie {
private Map<Character, Trie> map;
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Trie trie = new Trie();
trie.insert("boxing");
trie.insert("box");
System.out.println(trie.search("boxing"));
System.out.println(trie.startsWith("box"));
System.out.println(trie.search("box"));
}
/** Initialize your data structure here. */
public Trie() {
map = new HashMap<>();
}
/** Inserts a word into the trie. */
public void insert(String word) {
if (word != null) {
add(0, word, word.length());
}
}
private void add(int i, String word, int length) {
if (i < length) {
char c = word.charAt(i);
Trie subTrie = map.get(c);
if (subTrie == null) {
subTrie = new Trie();
map.put(c, subTrie);
}
subTrie.add(i + 1, word, length);
} else map.put(null, new Trie()); // use null to indicate end of string
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
if (word != null) {
return search(0, word, word.length());
}
return false;
}
private boolean search(int i, String word, int length) {
if (i < length) {
char c = word.charAt(i);
Trie subTrie = map.get(c);
if (subTrie == null) return false;
return subTrie.search(i + 1, word, length);
}
return map.containsKey(null);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
if (prefix != null) {
return startsWith(0, prefix, prefix.length());
}
return false;
}
private boolean startsWith(int i, String prefix, int length) {
if (i < length) {
char c = prefix.charAt(i);
Trie subTrie = map.get(c);
if (subTrie == null) return false;
return subTrie.startsWith(i + 1, prefix, length);
} else return true;
}
}