-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.java
executable file
·74 lines (60 loc) · 1.91 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
import java.util.HashMap;
import java.util.Map;
public class Trie {
class TriNode {
private Map<Character, TriNode> triNodeMap;
private boolean isLast;
public Map<Character, TriNode> getTriNodeMap(){
return this.triNodeMap;
}
public boolean isLast(){
return this.isLast;
}
public void setIsLast(boolean isLast){
this.isLast = isLast;
}
public TriNode(){
this.triNodeMap = new HashMap<>();
}
}
private TriNode triNode;
public Trie() {
this.triNode = new TriNode();
}
public void insert(String word) {
TriNode temp = this.triNode;
char[] characters = word.toCharArray();
for(int i=0; i<characters.length;i++){
if(!temp.getTriNodeMap().containsKey(characters[i]))
temp.getTriNodeMap().put(characters[i], new TriNode());
if(i == characters.length-1)
temp.setIsLast(true);
temp = temp.getTriNodeMap().get(characters[i]);
}
}
public boolean search(String word) {
var temp = triNode;
char[] characters = word.toCharArray();
for(int i=0; i<characters.length; i++){
if(!temp.getTriNodeMap().containsKey(characters[i])){
return false;
}
if(i==characters.length-1 && !temp.isLast()){
return false;
}
temp = temp.getTriNodeMap().get(characters[i]);
}
return true;
}
public boolean startsWith(String prefix) {
var temp = triNode;
char[] characters = prefix.toCharArray();
for(char character : characters){
if(! temp.getTriNodeMap().containsKey(character)){
return false;
}
temp = temp.getTriNodeMap().get(character);
}
return true;
}
}