Given two stringssandt, write a function to determine iftis an anagram ofs.
For example,
s= "anagram",t= "nagaram", return true.
s= "rat",t= "car", return 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?
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() == 0 && t.length() == 0) {
return true;
} else if (s.length() == 0) {
return false;
}
Map<Character, Integer> freq = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (!freq.containsKey(s.charAt(i))) {
freq.put(s.charAt(i), 1);
} else {
freq.put(s.charAt(i), freq.get(s.charAt(i)) + 1);
}
}
for (int i = 0; i < t.length(); i++) {
if (!freq.containsKey(t.charAt(i)) || freq.get(t.charAt(i)) == 0) {
return false;
}
freq.put(t.charAt(i), freq.get(t.charAt(i)) - 1);
}
for (Character c : freq.keySet()) {
if (freq.get(c) != 0) {
return false;
}
}
return true;
}
}
时间复杂度O(N), 空间O(1).