Accepted JAVA Solution Use HashMap Record Char and Its Frequency


  • 0
    F
    public class Solution {
        public boolean isAnagram(String s, String t) {
            Map<Character, Integer> map = new HashMap<>();
            // Store character and its frequencey in map
            for(int i=0; i<s.length(); i++){
                char c = s.charAt(i);
                if(map.containsKey(c)){
                    map.put(c, map.get(c)+1);
                }else{
                    map.put(c, 1);
                }
            }
            // check record with the String t
            for(int i=0; i<t.length(); i++){
                char c = t.charAt(i);
                if(map.containsKey(c)){
                    // Last one, remove key from map
                    if(map.get(c)==1){
                        map.remove(c);
                    }else{ 
                        map.put(c, map.get(c)-1);
                    }
                }else{// cannot find such character in original String
                    return false;
                }
            }
            return map.isEmpty();
        }
    }

  • 0
    K

    A array may be much simpler and quicker than HashMap. Array is always better than HashMap if we do not need to calculate the frequency of complex data items like String.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.