I am writing a code for CodeChef. but getting error TLE is it possible to optimize it more?

V_for_Vj :

I am writing a code for CodeChef. but getting error TLE (2.10000) is it possible to optimize it more?

Question Link: https://www.codechef.com/APRIL19B/problems/STRCH

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 main (String[] args) throws java.lang.Exception
    {
         Scanner ss = new Scanner(System.in);
         int  T = ss.nextInt();

             for(int k=0;k<T;k++){

                         int counter=0;
                         int N=ss.nextInt();
                         String S=ss.next();
                         char c=ss.next().charAt(0);
                         int sLengthOne=S.lastIndexOf(c);
                         int sLengthTwo=S.length();
                         if(S.length()==N){
                                 for (int i = 0; i <= sLengthOne; i++) {
                                    for (int j = 1; j <= sLengthTwo-i; j++) {
                                        if(S.substring(i,i+j).indexOf(c)!=-1){
                                            counter++;
                                        }
                                    }
                                }
                         System.out.println(counter);
                         }
         }

    }
}
Chitransh Shrivastava :

When you try to generate all the possible substrings for the given string, it increases a lot of processing time for your code. Instead, try to work out the solution mathematically by calculating the substrings without actually generating them and then check whether the index of the letter which needs to be found is present in that substring range or not.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=150134&siteId=1