congr / world

2 stars 1 forks source link

LeetCode : 242. Valid Anagram #400

Closed congr closed 6 years ago

congr commented 6 years ago

https://leetcode.com/problems/valid-anagram/description/

image

congr commented 6 years ago

O(NLogN) solution is sorting 2 arrays and match it one by one.

O(N) is using map or array.

class Solution {
    public boolean isAnagram(String s, String t) {
        Map<Character, Integer> map = new HashMap();

        for (char c : s.toCharArray()) map.merge(c, 1, Integer::sum);
        for (char c : t.toCharArray()) map.merge(c, -1, Integer::sum);

        for (Character c : map.keySet()) 
            if (map.get(c) != 0) return false;

        return true;
    }
}