Skip to content

Commit f80c66f

Browse files
Add files via upload
1 parent f119eb5 commit f80c66f

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

AUTO COMPLETE.txt

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import java.util.*;
2+
class TrieNode{
3+
char data;
4+
boolean isTerminating;
5+
TrieNode children[];
6+
int childCount;
7+
8+
public TrieNode(char data) {
9+
this.data = data;
10+
isTerminating = false;
11+
children = new TrieNode[26];
12+
childCount = 0;
13+
}
14+
}
15+
16+
public class Trie {
17+
private TrieNode root;
18+
19+
public Trie() {
20+
root = new TrieNode('\0');
21+
}
22+
23+
private void add(TrieNode root, String word){
24+
if(word.length() == 0){
25+
root.isTerminating = true;
26+
return;
27+
}
28+
int childIndex = word.charAt(0) - 'a';
29+
TrieNode child = root.children[childIndex];
30+
if(child == null){
31+
child = new TrieNode(word.charAt(0));
32+
root.children[childIndex] = child;
33+
root.childCount++;
34+
}
35+
add(child, word.substring(1));
36+
}
37+
38+
public void add(String word){
39+
add(root, word);
40+
}
41+
42+
public TrieNode findword(TrieNode root, String word) {
43+
if(word.length() == 0){
44+
return root;
45+
}
46+
int childIndex = word.charAt(0) - 'a';
47+
TrieNode child = root.children[childIndex];
48+
if(child == null){
49+
return null;
50+
}
51+
return findword(child, word.substring(1));
52+
}
53+
54+
public void allwords(TrieNode root,String word,String output){
55+
if(root==null)
56+
return;
57+
if(root.childCount == 0) {
58+
if(output.length() > 0) {
59+
System.out.println(word + output);
60+
}
61+
return;
62+
}
63+
if(root.isTerminating == true) {
64+
System.out.println(word + output);
65+
}
66+
67+
for(int i = 0; i < root.children.length; i++) {
68+
if(root.children[i] != null) {
69+
String ans = output + root.children[i].data;
70+
allwords(root.children[i],word,ans);
71+
}
72+
}
73+
}
74+
public void autoComplete(ArrayList<String> input, String word){
75+
// for(String w : input) {
76+
// add(w);
77+
// }
78+
int i=0;
79+
while(i<input.size()){
80+
String a=input.get(i);
81+
add(root,a);
82+
i++;
83+
}
84+
if(root == null || root.childCount == 0) {
85+
return;
86+
}
87+
TrieNode a=findword(root,word);
88+
String output = "";
89+
allwords(a,word,output);
90+
}
91+
}

0 commit comments

Comments
 (0)