Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
The hint is given in problem description. Explore all pairs if they are anagrams.
I created solution in:
All solutions are also available on my GitHub profile.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class SherlockAndAnagrams { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for (int i = 0; i < tests; i++) { String string = stdin.nextLine(); int stringLength = string.length(); long resultPairs = 0; for (int length = 1; length <= stringLength; length++) { for (int start1 = 0; start1 < stringLength; start1++) { for (int start2 = start1 + 1; start2 < stringLength; start2++) { int end1 = start1 + length; int end2 = start2 + length; if(end1 <= stringLength && end2 <= stringLength) { String substring1 = string.substring(start1, end1); String subString2 = string.substring(start2, end2); if(toCharacterCount(substring1).equals( toCharacterCount(subString2))) { resultPairs++; } } } } } System.out.println(resultPairs); } stdin.close(); } private static Map<Character, Integer> toCharacterCount(String word) { Map<Character, Integer> result = new HashMap<>(); for (char c : word.toCharArray()) { if(result.containsKey(c)) { result.put(c, result.get(c) + 1); } else { result.put(c, 1); } } return result; } } |