Closed congr closed 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;
}
}
https://leetcode.com/problems/valid-anagram/description/