Accepted Java solution using two Maps


  • 0
    R
    public class Solution {
        public boolean isAnagram(String s, String t) {
            Map<Character,Integer> sChars = new HashMap<>();
            Map<Character,Integer> tChars = new HashMap<>();
            if (s.length() != t.length()) return false;
            for (int i = 0; i<s.length(); i++) {
                addToMap(sChars, s.charAt(i));
                addToMap(tChars, t.charAt(i));
            }
            return sChars.equals(tChars);
        }
        private void addToMap(Map<Character,Integer> map, char c) {
            if (map.keySet().contains(c)) {
                map.put(c,map.get(c)+1);
            } else {
                map.put(c,1);
            }
        }
    }

Log in to reply
 

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