Untitled
unknown
plain_text
2 years ago
1.5 kB
10
Indexable
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();
}
}
Editor is loading...
Leave a Comment