-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.java
57 lines (48 loc) · 1.33 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
/*
* Leetcode 208: Implement Trie (Prefix Tree)
* https://leetcode.com/problems/implement-trie-prefix-tree/
* Martin.Xia
*/
//Trie Node
class TrieNode{
//Or we could use HashSet instead of TrieNode
public TrieNode[] children = new TrieNode[26];
//Or we could use a boolean value to save is leaf node or not
public String item = "";
}
//Trie
public class Trie{
public TrieNode root = new TrieNode();
public void insert(String word){
TrieNode node = root;
for(char c: word.toCharArray()){
if(node.children[c-'a']==null){
node.children[c-'a']= new TrieNode();
}
node = node.children[c-'a'];
}
node.item = word;
}
public boolean search(String word){
TrieNode node = root;
for(char c: word.toCharArray()){
if(node.children[c-'a']==null)
return false;
node = node.children[c-'a'];
}
if(node.item.equals(word)){
return true;
}else{
return false;
}
}
public boolean startsWith(String prefix){
TrieNode node = root;
for(char c: prefix.toCharArray()){
if(node.children[c-'a']==null)
return false;
node = node.children[c-'a'];
}
return true;
}
}