We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
/*
* Complete the 'sherlockAndAnagrams' function below.
*
* The function is expected to return an INTEGER.
* The function accepts STRING s as parameter.
*/
public static int sherlockAndAnagrams(String s) {
Map<String, Integer> freqMap = new HashMap<>();
int n = s.length();
// Generate all substrings
for (int i = 0; i < n; i++) {
int[] count = new int[26];
for (int j = i; j < n; j++) {
count[s.charAt(j) - 'a']++;
StringBuilder key = new StringBuilder();
for (int k = 0; k < 26; k++) {
key.append(count[k]).append('#');
}
String signature = key.toString();
freqMap.put(signature, freqMap.getOrDefault(signature, 0) + 1);
}
}
int totalPairs = 0;
for (int val : freqMap.values()) {
totalPairs += (val * (val - 1)) / 2;
}
return totalPairs;
}
}
public class Solution {
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 = Result.sherlockAndAnagrams(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and Anagrams
You are viewing a single comment's thread. Return to all comments →
import java.io.; import java.util.;
class Result {
}
public class Solution { 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")));
}