242. Valid Anagram (Easy)
https://leetcode.com/problems/valid-anagram/
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Example 2:
Input: s = "rat", t = "car" Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Solutions
class Solution {
// Calculate the char frequency for each str, then compare if identical.
public boolean isAnagram(String s, String t) {
if (s == null && t == null) {
return true;
}
if (s == null) {
return false;
}
if (t == null) {
return false;
}
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> countMap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (!countMap.containsKey(c)) {
countMap.put(c, 0);
}
countMap.put(c, countMap.get(c) + 1);
}
for (int i = 0; i < t.length(); i++) {
Character c = t.charAt(i);
if (!countMap.containsKey(c)) {
return false;
}
countMap.put(c, countMap.get(c) - 1);
if (countMap.get(c) < 0) {
return false;
}
}
return true;
}
}