its jumping 2 whenever i recursive call it but i want it to jump only 1. and also when i run it its runs but when i submit it, it shows run time error
My code
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void recur(String s ,int idx , int count , HashSet<String> hash)
{
if(s.length()==1){
System.out.println(count);
return;
}
String temp = s.substring(idx , idx+2);
if(!hash.contains(temp))
{
count++;
hash.add(temp);
//System.out.println(temp);
}
idx = idx + 1;
recur(s.substring(idx) , idx , count , hash);
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
String s = sc.next();
HashSet<String> hash = new HashSet<>();
recur(s ,0 , 0 , hash);
//System.out.println(ans);
}
}
}
thank you sir but i’m trying to do it with recursion .i’m having a problem which is
whenever i try to call recur function after 1st call it takes jump of 2 idx. for ex YBNA. so here the correct ans will be 3 as YB , BN , NA . but when i call it it jumps two idx . so my ans for YBNA is YB , NA so count is 2 . thats the problem im facing
@co2annu
just few little mistakes in your code .
I have corrected it in your code . Hope u will get it
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void recur(String s ,int idx , int count , HashSet<String> hash)
{
if(s.length()-1==idx){
System.out.println(count);
return;
}
String temp = s.substring(idx , idx+2);
if(!hash.contains(temp))
{
count++;
hash.add(temp);
//System.out.println(temp);
}
recur(s, idx+1 , count , hash);
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
String s = sc.next();
HashSet<String> hash = new HashSet<>();
recur(s ,0 , 0 , hash);
//System.out.println(ans);
}
}
}