Below is the code for the problem at Codechef. I have made use of the String
method .equals
in my solution which is working fine for all the test inputs. However, I am getting a Time Limit Exceeded when I submit to the Judge. I need your ideas on optimizing the code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
public static void main(String args[]) throws IOException
{
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
int not=Integer.parseInt(in.readLine());
for(int i=0;i<not;i++)
{
String s=in.readLine();
int count=0;
String inp[]=in.readLine().trim().split(" ");
int m=Integer.parseInt(inp[0]);
int p=Integer.parseInt(inp[1]);
//System.out.println(m+" "+p);
String temp=s;
for(int b=0;b<(Integer.MAX_VALUE/2);b++)
{
//System.out.println(temp);
String s1=rotate(m,temp);
//System.out.println(s1);
count++;
if(s1.equals(s))
break;
String s2=rotate(p,s1);
//System.out.println(s2);
count++;
if(s2.equals(s))
break;
temp=s2;
}
if(count>0)
System.out.println(count);
else
System.out.println(-1);
}
} private static String rotate(int m, String s) {
char sa[]=s.toCharArray();
int l=sa.length;
StringBuilder sb=new StringBuilder();
for(int j=m-1;j>=0;j--)
{
sb.append(sa[l-1-j]);
}
for(int k=0;k<(l-m);k++)
sb.append(sa[k]);
return sb.toString();
}
}