PLEASE TELL ME WHERE I AM DOING MISTAKE? NONE OF THE TEST CASES ARE PASSING ON SUBMISSION THOUGH MY MANUAL TEST CASES PASSED.
import java.util.*;
public class Dictionary
{
private class Node
{
char data;
HashMap<Character,Node> children;
boolean isTerminal;
Node(char data,boolean isTerminal)
{
this.data=data;
this.children=new HashMap<>();
this.isTerminal=isTerminal;
}
}
private int numWords;
private Node root;
Dictionary()
{
this.root=new Node('\0',false);
numWords=0;
}
public int numWords()
{
return this.numWords;
}
public void addWord(String word)
{
this.addWord(this.root,word);
}
private void addWord(Node parent,String word)
{
if(word.length()==0)
{
if(parent.isTerminal)
{
//Word already added
}
else
{
parent.isTerminal=true;
this.numWords++;
}
return;
}
char cc=word.charAt(0);
String ros=word.substring(1);
Node child=parent.children.get(cc);
if(child==null)
{
child=new Node(cc,false);
parent.children.put(cc,child);
}
this.addWord(child,ros);
}
private ArrayList<String> display(Node node,String osf,ArrayList<String> list)
{
if(node.isTerminal)
{
String toDisplay=osf+node.data;
list.add(toDisplay);
}
Set<Map.Entry<Character,Node>> entries=node.children.entrySet();
for(Map.Entry<Character,Node> entry:entries)
{
this.display(entry.getValue(),osf+node.data,list);
}
return list;
}
public void search(String word)
{
this.search(this.root,word,"");
}
private void search(Node parent,String word,String temp)
{
if(word.length()==0)
{
ArrayList<String> list=new ArrayList<>();
ArrayList<String> l=this.display(parent,temp.substring(0,temp.length()-1),list);
l.sort(null);
for(String st:l)
{
System.out.println(st);
}
return;
}
char cc=word.charAt(0);
String ros=word.substring(1);
Node child=parent.children.get(cc);
if(child==null)
{
System.out.println("No suggestions");
return;
}
search(child,ros,temp+cc);
}
public static void main(String[] args)
{
Dictionary trie=new Dictionary();
Scanner sc=new Scanner(System.in);
int i,n=sc.nextInt();
for(i=0;i<n;i++)
{
String str=sc.next();
trie.addWord(str);
}
int Q=sc.nextInt();
for(i=1;i<=Q;i++)
{
String s=sc.next();
trie.search(s);
}
}
}