Sherlock and Anagrams

Sherlock and Anagrams

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the sherlockAndAnagrams function below.
    static int sherlockAndAnagrams(String s) {
        ArrayList subStrings = new ArrayList();
        for(int i = 1; i <= s.length(); i++){
            if(( i%s.length()) == i){
                subStrings.addAll(generateSubstring(s,i));
            }
        }

        int palindroms=0;
        for (int i = 0; i < subStrings.size(); i++){
            for (int j = i+1; j < subStrings.size(); j++){
                if (isPalindrom(subStrings.get(i),subStrings.get(j)))
                palindroms++;
            }
        }
    return palindroms;
    }
    static boolean isPalindrom(String a, String b){
        if(a.length() != b.length()) return false;
        char [] ac = a.toCharArray();
        char [] bc = b.toCharArray();
        Arrays.sort(ac);
        Arrays.sort(bc);
        for(int i = 0; i < ac.length; i++){
            if(ac[i] != bc[i]) return false;
        }
        return true;
    }
    static List generateSubstring (String a, int b){
        List out = new ArrayList();
        for (int i = 0; i < a.length() - b +1; i++){
                out.add(a.substring(i,i+b));
        }
        return out;
    }
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int q = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int qItr = 0; qItr < q; qItr++) {
            String s = scanner.nextLine();

            int result = sherlockAndAnagrams(s);

            bufferedWriter.write(String.valueOf(result));
            bufferedWriter.newLine();
        }

        bufferedWriter.close();

        scanner.close();
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s