Sherlock and Anagrams

  • + 0 comments

    Java

    public static int sherlockAndAnagrams(String s) {
            int count = 0;
            Map<String, Integer> map = new HashMap<>();
    
            for (int i = 0; i < s.length(); i++) {
                for (int j = i + 1; j <= s.length(); j++) {
                    String substring = s.substring(i, j);
                    char[] chars = substring.toCharArray();
                    Arrays.sort(chars);
                    String sortedSubstring = new String(chars);
    
                    map.put(sortedSubstring, map.getOrDefault(sortedSubstring, 0) + 1);
                }
            }
    
            for (int value : map.values()) {
                count += value * (value - 1) / 2; // combination formula is n * (n - 1) / 2
            }
    
            return count;
        }