I have a brute force solution to compute all the substrings in the input string in O (n ^ 2) time. It takes a lot of time when my input line is very long.
How to find all substrings in O (n) time?
I am only looking for the number of substrings where the first and last characters in the substring are the same. As you can see, I only return the account from the function to my code below. I want to do it in O (n) time
My brute force solution:
// I am calculating count of all substrings where first and last substring character are equal public class Solution { public static void main(String[] args) { String inputString = "ababaca"; System.out.println(findSubstringByBruteForcce(inputString, inputString.length())); } private static long findSubstringByBruteForcce(String inputString, int length) { long count = 0; for (int i = 0; i < length; i++) { for (int j = 1; j <= length - i; j++) { String str = inputString.substring(i, i + j); if(str.length() == 1){ count = count + 1; }else { if(str.substring(0, 1).equals(str.substring(str.length() - 1, str.length()))){ count = count + 1; } } } } return count; } }
How can I optimize the solution above and find the answer in O (N) time? The input string can be very large (approximately 10 ^ 6 lengths), and brute force works after about 20 seconds. I want the maximum execution time to be less than 2 seconds.
source share