package Trie;
import java.util.*;
public class Implementation {
private class node{
char data;
HashMap<Character,node> children=new HashMap<>();
boolean isterminal;
// node()
}
private node root;
private int nofwords;
Implementation(){
root=new node();
root.data=’\0’;
}
public void add(String str) {
add(root,str);
// a
}
private void add(node parent,String str) {
if(str.length()==0) {
if(parent.isterminal) {
return;
}
parent.isterminal=true;
nofwords++;
return;
}
char c=str.charAt(0);
String ros=str.substring(1);
if(parent.children.containsKey(c)) {
add(parent.children.get(c),ros);
}
else {
node nn=new node();
nn.data=c;
parent.children.put(c,nn);
add(nn,ros);
}
}
public void display() {
display(root,"");
}
public void display(node parent,String ans)
{
for(char c:parent.children.keySet()) {
display(parent.children.get(c),ans+c);
}
if(parent.isterminal) {
System.out.println(ans);
}
}
public boolean search(String str) {
int x=str.length();
node parent=root;
for(int i=0;i<x;i++) {
char c=str.charAt(i);
if(parent.children.containsKey(c)) {
parent=parent.children.get(c);
continue;
}
return false;
}
return true;
}
public void similarwords(String str) {
int x=str.length();
node parent=root;
for(int i=0;i<x;i++) {
char c=str.charAt(i);
if(parent.children.containsKey(c)) {
parent=parent.children.get(c);
}
else {
// System.out.println(“ADDING THE WORDS BCS NOT FOUND”);
add(str);
// display();
return;
}
}
// System.out.print("WORDS ARE: " );
ArrayList list=new ArrayList<>();
displayAnswer(parent,str,list);
Collections.sort(list);
for(String k:list) {
System.out.println(k);
}
}
public ArrayList<String> displayAnswer(node parent,String str,ArrayList<String> list) {
for(char ch:parent.children.keySet()) {
displayAnswer(parent.children.get(ch),str+ch,list);
}
if(parent.isterminal) {
list.add(str);
}
return list;
}
// public boolean search(String str) {
//
// int x=str.length();
// node parent=root;
// for(int i=0;i<x;i++) {
// char c=str.charAt(i);
//
// }
//
// return true;
// }
public static void main(String[] args) {
// TODO Auto-generated method stub
// String[] arr= {“ashu”,“ashui”,“rat”,“cat”,“catty”,“cas”,“cater”,“castle”,“zer”,“213”,“rati”,“zee”,“zeekjhk”,“2”,“pop”,“peopy”,“champion”,“break”};
Implementation tr=new Implementation();
// String[] arr= {“ashu”,“ashi”,“cat”,“catty”};
// for(int i=0;i<arr.length;i++) {
// tr.add(arr[i]);
// }
// tr.display();
// System.out.println();
// System.out.println("STARTING THE SEARCHNG PROCESS : ");
// System.out.println(tr.search(“2”));
// System.out.println(tr.search(“break”));
// System.out.println(tr.search(“1234”));
// tr.similarwords(“2”);
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
for(int i=0;i<n;i++) {
tr.add(scanner.next());
}
int m=scanner.nextInt();
for(int i=0;i<m;i++) {
tr.similarwords(scanner.next());
}
}
}
This is my code