Source

class Solution {
    public boolean closeStrings(String word1, String word2) {
        if(word1.length() != word2.length()){
            return false;
        }
 
        Map<Character, Integer> fMap1 = new HashMap<>();
        Map<Character, Integer> fMap2 = new HashMap<>(); 
 
        for(Character c : word1.toCharArray()){
            fMap1.put(c, fMap1.getOrDefault(c, 0) + 1);
        }
 
        for(Character c : word2.toCharArray()){
            fMap2.put(c, fMap2.getOrDefault(c, 0) + 1);
        }
 
        if(!fMap2.keySet().equals(fMap1.keySet())){
            return false;
        }
 
        List<Integer> w1 = new ArrayList<>(fMap1.values());
        List<Integer> w2 = new ArrayList<>(fMap2.values());
 
        Collections.sort(w1);
        Collections.sort(w2);
 
        return w1.equals(w2);
    }
}