-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTriesQ4.java
More file actions
77 lines (61 loc) · 1.92 KB
/
TriesQ4.java
File metadata and controls
77 lines (61 loc) · 1.92 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
public class TriesQ4 {
static class Node {
Node[] children = new Node[26];
boolean eow; // end of word
public Node() {
for (int i = 0; i < 26; i++) {
children[i] = null;
}
}
}
public static Node root = new Node();
public static void insert(String word) { // O(n)
int level = 0;
int len = word.length();
int idx = 0;
Node curr = root;
for (; level < len; level++) {
idx = word.charAt(level) - 'a';
if (curr.children[idx] == null) {
curr.children[idx] = new Node();
}
curr = curr.children[idx];
}
curr.eow = true;
}
public static boolean search(String key) { // O(n)
int level = 0;
int len = key.length();
int idx = 0;
Node curr = root;
for (; level < len; level++) {
idx = key.charAt(level) - 'a';
if (curr.children[idx] == null) {
return false;
}
curr = curr.children[idx];
}
return curr.eow;
}
public static void longestWord(Node root, StringBuilder curr) {
for(int i=0; i<26; i++) {
if(root.children[i] != null && root.children[i].eow == true) {
curr.append((char)(i+'a'));
if(curr.length() > ans.length()) {
ans = curr.toString();
}
longestWord(root.children[i], curr);
curr.deleteCharAt(curr.length()-1);
}
}
}
public static String ans = "";
public static void main(String args[]) {
String words[] = {"a","banana","app","appl","ap","apply"};
for (int i = 0; i < words.length; i++) {
insert(words[i]);
}
longestWord(root, new StringBuilder(""));
System.out.println(ans);
}
}