-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
88 lines (72 loc) · 2.39 KB
/
Trie.java
File metadata and controls
88 lines (72 loc) · 2.39 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
package DataStructures;
public class Trie {
static class TrieVertex {
int wordCount;
int prefixCount;
TrieVertex[] edges;
public TrieVertex(){
wordCount = 0;
prefixCount = 0;
edges = new TrieVertex[26];
for(int i=0; i < edges.length; i++){
edges[i] = null; // init to no edges
}
}
}
public void addWord(TrieVertex vertex, String word){
if(word.length() == 0){
vertex.wordCount += 1;
} else {
vertex.prefixCount += 1;
char k = word.charAt(0);
if(!exists(vertex.edges, k)){
vertex.edges[k - 'a'] = new TrieVertex();
}
String nextPrefix = word.substring(1);
addWord(vertex.edges[k - 'a'], nextPrefix);
}
}
public int countWords(TrieVertex vertex, String word){
if(word.length() == 0){
return vertex.wordCount;
}
char k = word.charAt(0);
if(!exists(vertex.edges, k)) {
return 0;
} else {
String nextPrefix = word.substring(1);
return countWords(vertex.edges[k - 'a'], nextPrefix);
}
}
public int countWordsOffByOne(TrieVertex vertex, String word, Integer missingLetters){
if(word.length() == 0){
return vertex.wordCount;
}
char k = word.charAt(0);
if(!exists(vertex.edges, k) && missingLetters == 0){
return 0;
} else if(!exists(vertex.edges, k)){
String newPrefix = word.substring(1);
return countWordsOffByOne(vertex, newPrefix, missingLetters-1);
}
String newPrix = word.substring(1);
int r = countWordsOffByOne(vertex, newPrix, missingLetters-1);
r += countWordsOffByOne(vertex.edges[k - 'a'], newPrix, missingLetters);
return r;
}
public int countPrefixes(TrieVertex vertex, String word){
if(word.length() == 0){
return vertex.prefixCount;
}
char k = word.charAt(0);
if(!exists(vertex.edges, k)){
return 0;
} else {
String nextPrefix = word.substring(1);
return countPrefixes(vertex.edges[k - 'a'], nextPrefix);
}
}
private boolean exists(TrieVertex[] edges, char character){
return edges[character - 'a'] != null;
}
}