Two HashMap solution Java


  • 0
    A
    public class Solution {
    
    Map<Character, Integer> fstMap = new HashMap<Character, Integer>();
    Map<Character, Integer> sndMap = new HashMap<Character, Integer>();
    
    public boolean isAnagram(String s, String t) {
        fstMap.clear();
        sndMap.clear();
        int length = s.length();
        if(length != t.length()) {
            return false;
        }
    
        for(int i = 0; i < length; ++i) {
            if(!fstMap.containsKey(s.charAt(i))) {
                fstMap.put(s.charAt(i), 1);
            } else {
                int value = fstMap.get(s.charAt(i)) + 1;
                fstMap.remove(s.charAt(i));
                fstMap.put(s.charAt(i), value);
            }
            if(!sndMap.containsKey(t.charAt(i))) {
                sndMap.put(t.charAt(i), 1);
            } else {
                int value = sndMap.get(t.charAt(i)) + 1;
                sndMap.remove(t.charAt(i));
                sndMap.put(t.charAt(i), value);
            }
        }
    
        for(int i = 0; i < length; ++i) {
            if(!sndMap.containsKey(s.charAt(i))) {
                return false;
            }
            if(fstMap.get(s.charAt(i)).compareTo(sndMap.get(s.charAt(i))) != 0) {
                return false;
            }
        }
        return true;
    }
    

    }


Log in to reply
 

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