I am trying to solve the following question: https://www.hackerrank.com/challenges/sherlock-and-anagrams
This is my code
import java.util.*;
public class Solution {
public static boolean check(String s1,String s2)
{
int [] count1 = new int[26];
for( int i = 0; i < s1.length(); i++ )
{
char ch1 = s1.charAt(i);
count1[ch1-'a']++;
}
int [] count2 = new int[26];
for( int i = 0; i < s2.length(); i++ )
{
char ch2 = s2.charAt(i);
count2[ch2-'a']++;
}
int count =0;
for(int j=0;j<26;j++)
{
count = count + Math.abs(count1[j]-count2[j]);
}
if(count ==0)
return true;
else return false;
}
public static void main(String[] args) {
String s,sub;
int i,c,len;
List<String> all = new ArrayList<>();
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
while((t--)>0)
{
s = in.nextLine();
len = s.length();
for( c = 0 ; c < len ; c++ )
{
for( i = 1 ; i <= len - c ; i++ )
{
sub = s.substring(c, c+i);
all.add(sub);
}
}
String[] arr = new String[all.size()];
for( i = 0; i < all.size(); i++)
arr[i] = all.get(i);
int l=0;
for (int m=0;m<arr.length;m++)
{
for(int n=m+1;n<arr.length;n++)
{
if(check(arr[m],arr[n]))
l++;
}
}
System.out.println(l);all.clear();
}
}
}
My code worked for few test cases which have small strings but failed to work if string size is too big
Sample input
5
ifailugtyovhdfuhdouarjsnrbfpvmupwjjjfiwneogwnoegnoegneognoewhrlkpekxxnebfrwibylcvkfealgonjkzw
gffryqktmwocejbrexfidpjfgrrkpowoxwggxaknmltjcpazgtnakcfbveieivoenwvpnoevvneocogzatyskqjyorcftw
uqlzvuzgkwhkkrrfpwarkckansgabfclzgnumdrojexnofeqjnqnxwidhbvbenevun9evnnv9euxxhfwargwkikjq
sygjxynvofnvirarcoacwnhxyqlrviikfuiuotifznqmzpjrxycnqkeibvibvewioebvitkryutpqvbgbgthfges
mkenscyiamnwlpxytkndjsygifmqlqibxxqlauxamfviftquntvkwppxrzuncyenavebiobeviobeiobeibvcfivtigv
My Output
4s : Terminated due to timeout
is there any better way to solve it or to change the existing code so that executed time is within 4mins