-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestWord.java
76 lines (69 loc) · 2.28 KB
/
LongestWord.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package Tries;
public class LongestWord {
static class Node {
Node[] children = new Node[26];
boolean endOfWord = false;
Node() {
for (int i = 0; i < 26; i++) {
// by default these are null values
children[i] = null;
}
}
}
// declaring empty Root node
public static Node root = new Node();
// Insert into trie
public static void insert(String word){ //O[L]
Node curr = root;
for (int level = 0; level <word.length(); level++){
int index = word.charAt(level) - 'a';
if (curr.children[index] == null){
// create node : if does not exist
curr.children[index] = new Node();
}
curr = curr.children[index];
}
curr.endOfWord = true;
}
// Search into trie
public static boolean search(String key){
Node curr = root;
for (int level=0; level<key.length(); level++){
int index = key.charAt(level) - 'a';
if (curr.children[index] == null){
// last condition
return false;
}
curr = curr.children[index];
}
if (curr.endOfWord == true) return true;
else return false;
}
public static String ans = "";
public static void longestWord(Node root, StringBuilder tmp){
if (root == null) {
return;
}
for (int i=0; i<26; i++){
if (root.children[i] != null && root.children[i].endOfWord == true){
char ch = (char)(i +'a');
tmp.append(ch);
if (tmp.length() > ans.length()) {
ans = tmp.toString();
}
longestWord(root.children[i], tmp);
//backtrack
tmp.deleteCharAt(tmp.length()-1);
}
}
}
public static void main(String[] args) {
String[] words = {"a","banana", "ap", "app", "apple", "apply"};
//inserting
for (int i=0; i<words.length; i++){
insert(words[i]);
}
longestWord(root, new StringBuilder(" "));
System.out.println(ans);
}
}