-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplement Trie
91 lines (83 loc) · 2.41 KB
/
Implement Trie
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
90
91
/**
* Your Trie object will be instantiated and called as such:
* Trie trie = new Trie();
* trie.insert("lintcode");
* trie.search("lint"); will return false
* trie.startsWith("lint"); will return true
*/
class TrieNode {
// Initialize your data structure here.
public char c;
public TrieNode[] next = new TrieNode[26];
public boolean isLeaf;
public TrieNode() {
}
public TrieNode(char c) {
this.c = c;
}
public void setToLeaf() {
this.isLeaf = true;
}
public boolean isLeaf() {
return this.isLeaf;
}
}
public class Solution {
private TrieNode root;
public Solution() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
if (word == null || word.length() == 0) {
return;
}
//the runner to traverse the trie
TrieNode cur = root;
//traverse the trie, if null make a new node
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
int index = c - 'a';
if (cur.next[index] == null) {
cur.next[index] = new TrieNode(c);
}
cur = cur.next[index];
}
cur.setToLeaf();
}
// Returns if the word is in the trie.
public boolean search(String word) {
if (word == null || word.length() == 0) {
return false;
}
//search starts from root
TrieNode cur = root;
//if this char's corresponding node is null, return false
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
int index = c - 'a';
if (cur.next[index] == null) {
return false;
}
cur = cur.next[index];
}
return cur.isLeaf();
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
if (prefix == null) {
return false;
}
TrieNode cur = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
int index = c - 'a';
if (cur.next[index] == null) {
return false;
}
cur = cur.next[index];
}
return true;
}
}