Untitled

mail@pastecode.io avatar
unknown
plain_text
21 days ago
1.5 kB
3
Indexable
Never
import java.io.*;
import java.util.*;

public class Solution {

    static int sherlockAndAnagrams(String s) {
        HashMap<String, Integer> map = new HashMap<>();
        int totalCount = 0;

        // Generate all substrings
        for (int i = 0; i < s.length(); i++) {
            for (int j = i; j < s.length(); j++) {
                char[] substring = s.substring(i, j + 1).toCharArray();
                Arrays.sort(substring);  // Sort the characters to normalize
                String sortedSubstring = new String(substring);
                map.put(sortedSubstring, map.getOrDefault(sortedSubstring, 0) + 1);
            }
        }

        // Count pairs of anagrammatic substrings
        for (int count : map.values()) {
            totalCount += (count * (count - 1)) / 2;
        }

        return totalCount;
    }

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

        int q = Integer.parseInt(bufferedReader.readLine().trim());

        for (int qItr = 0; qItr < q; qItr++) {
            String s = bufferedReader.readLine();
            int result = sherlockAndAnagrams(s);
            bufferedWriter.write(String.valueOf(result));
            bufferedWriter.newLine();
        }

        bufferedReader.close();
        bufferedWriter.close();
    }
}
Leave a Comment