Simple Java Map solution


  • 1
    J
     public boolean isAnagram(String s, String t) {
        if (s.length() != t.length())
        	return false;
        Map<Character, Integer> map = new HashMap<>();
        for (char c : s.toCharArray()) {
        	map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (char c : t.toCharArray()) {
        	if (map.containsKey(c)) {
        		int count = map.get(c);
        		if (count == 1)
        			map.remove(c);
        		else 
        			map.put(c, count - 1);
        	}
        }
        return map.isEmpty();
    }

Log in to reply
 

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