-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrefixProblem.java
58 lines (48 loc) · 1.43 KB
/
PrefixProblem.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
package Tries;
public class PrefixProblem {
public static class Node {
Node[] children = new Node[26];
boolean eow;
int freq;
public Node(){
for (int i=0; i<26; i++){
children[i] = null;
}
freq = 1;
}
}
public static Node root = new Node();
public static void insert(String word){
Node curr = root;
for (int i=0; i<word.length(); i++){
int index = word.charAt(i)-'a';
if (curr.children[index] == null){
curr.children[index] = new Node();
}else{
curr.children[index].freq++;
}
curr = curr.children[index];
}
curr.eow = true;
}
public static void main(String[] args) {
String[] words = {"zebra", "dog", "duck", "dove"};
for (int i=0; i<words.length; i++){
insert(words[i]);
}
root.freq = -1;
findPrefix(root, "");
}
private static void findPrefix(Node root, String ans) {
if (root == null) return;
if (root.freq == 1) {
System.out.println(ans);
return;
}
for (int i=0; i<root.children.length; i++){
if (root.children[i] != null){
findPrefix(root.children[i], ans+(char)(i + 'a') + " ");
}
}
}
}