-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
53 lines (40 loc) · 1.26 KB
/
Trie.java
File metadata and controls
53 lines (40 loc) · 1.26 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
class Trie {
private int length = 0;
private int totalLength = 0;
private ElementTrie first = new ElementTrie();
public String insertWord(String word){
ElementTrie child = first;
for (int i=0; i < word.length(); i ++){
if (child.getAlphabet()[ElementTrie.letterToIndex(word.charAt(i))] == null){
child.getAlphabet()[ElementTrie.letterToIndex(word.charAt(i))] = new ElementTrie(word.charAt(i));
}
child = child.getAlphabet()[ElementTrie.letterToIndex(word.charAt(i))];
}
if (! child.isWord){
this.length += 1;
child.isWord = true;
}
this.totalLength += 1;
return word;
}
public boolean has(String word){
ElementTrie child = first;
for (int i=0; i < word.length(); i ++){
ElementTrie node = child.getAlphabet()[ElementTrie.letterToIndex(word.charAt(i))];
if (node == null) {
return false;
}
child = node;
}
if (child.isWord) {
return true;
}
return false;
}
public int getLength(){
return this.length;
}
public int getTotalLength(){
return this.totalLength;
}
}