Sherlock and Anagrams

  • + 0 comments

    Java 8

    My solution :

     public static int sherlockAndAnagrams(String s) {
        
           Map<String,Integer> matchMap = new HashMap<>();
          
           for(int i= 0; i < s.length(); i++){
               for(int j= i+1; j <= s.length(); j++){
                    char[] array = s.substring(i, j).toCharArray();
                    Arrays.sort(array);
                    String orderSubString = String.valueOf(array);
                    matchMap.compute(orderSubString, (k,v) -> (v != null ? v : 0) + 1); 
               }
           }
           
           matchMap.replaceAll((k, v) -> IntStream.range(1, v).sum());
           return matchMap.values().stream().reduce(0, (a,b)-> a+b);
        }