-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
101 lines (77 loc) · 2.15 KB
/
Trie.java
File metadata and controls
101 lines (77 loc) · 2.15 KB
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
92
93
94
95
import java.util.*;
public class Trie<T>{
T node = null;
HashMap<Character, Trie<T>> children = new HashMap<>();
public T put(String word, T node){
return put(word, node, 0);
}
private T put(String word, T node, int i){
if(i == word.length()){
this.node = node;
return this.node;
}
else{
char c = word.charAt(i);
Trie<T> child;
if(!children.containsKey(c)){
children.put(c, new Trie<T>());
}
child = children.get(c);
return child.put(word, node, i+1);
}
}
public boolean containsKey(String word){
return this.get(word) != null;
}
public boolean remove(T n){
if(this.node != null && this.node.equals(n)){
node = null;
return true;
}
else{
for(Character c: children.keySet()){
if(children.get(c).remove(n))
return true;
}
return false;
}
}
public T get(String word){
return get(word, 0);
}
private T get(String word, int i){
if(i == word.length()){
return this.node;
}
else{
if(children.containsKey(word.charAt(i))){
Trie<T> child = children.get(word.charAt(i));
return child.get(word, i+1);
}
else
return null;
}
}
public Trie<T> getFirst(){
if(this.node != null)
return this;
else{
for(Character c : children.keySet()){
Trie<T> result = children.get(c).getFirst();
if(result != null)
return result;
}
return null;
}
}
public String toString(){
StringBuffer ret = new StringBuffer();
if(this.node != null){
ret.append(this.node.toString() + "\n");
}
for(char k: children.keySet()){
ret.append(children.get(k).toString());
}
return ret.toString();
}
}