简体   繁体   中英

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

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);
                         }
         }

    }
}

Your current code runs in O(n * n), you need to make it O(n). The idea is just to check in which positions there is the letter you need and use a bit of math to calculate the amount of substrings that contain that letter. You will also need to think of a strategy to avoid counting overlaps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM