Making Anagrams

  • + 0 comments

    Java solution based on calc the number of common charcters of each string

    public static int makingAnagrams(String s1, String s2) {
        int commonCount = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        int n = s1.length();
        int m = s2.length();
        
        for(int i = 0; i < n; i++){
          char c = s1.charAt(i);
          map.put(c, map.getOrDefault(c, 0) + 1 );
          }
        
        for(int i = 0; i < m; i++){
          char c = s2.charAt(i);
          if( map.containsKey(c) && map.get(c) > 0){
            commonCount++;
            map.put(c, map.get(c) - 1);
            }
          }
        
        return n + m - 2 * commonCount;
    
        }