Accepted Java Solution using HashMap (26% of Java submissions)

  • 1

    This is my solution using HashMap. Also would also appreciate if you guys can suggest more improvements to it or some other solutions. Cheers.

    public boolean isAnagram(String s, String t) {
            if(s.length() != t.length()) return false;
            HashMap<Character,Integer> map = new HashMap<>();
            for(Character c : s.toCharArray()){
                int count = map.getOrDefault(c,0)+1;
            for(Character c : t.toCharArray()){
                int count = map.getOrDefault(c,0)-1;
                if(count < 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.