My Java Solution Using HashMap: A bit slower though, process more than a~z.


  • 0
    W

    Although it is a little bit slower than the solution that only copes with a~z, it could deal with more than a~z. I'll appreciate if anyone could make it faster, especially in checking map.values section.

    public class Solution {
        public boolean isAnagram(String s, String t) {
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            for (int i = 0; i < s.length(); i++) {
                if (!map.containsKey(s.charAt(i))) {
                    map.put(s.charAt(i), 1);
                } else {
                    map.put(s.charAt(i), map.get(s.charAt(i))+1);
                }
            }
            for (int j = 0; j < t.length(); j++) {
                if (!map.containsKey(t.charAt(j))) {
                    return false;
                } else {
                    map.put(t.charAt(j), map.get(t.charAt(j))-1);
                }
            }
            List<Integer> list = new ArrayList<>(map.values());
            for(int k = 0 ;k <list.size();k++) {
                if (list.get(k) != 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.