/*
最优解
*/
public class Solution {
public boolean isAnagram(String s, String t) {
int[] arr = new int[26];
for (int i = 0; i < s.length(); i++) {
arr[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
arr[t.charAt(i) - 'a']--;
}
for (Integer count : arr) {
if (count != 0) {
return false;
}
}
return true;
}
}
/*
First version
*/
public class Solution {
public boolean isAnagram(String s, String t) {
char[] sArr = s.toCharArray();
char[] tArr = t.toCharArray();
Arrays.sort(sArr);
Arrays.sort(tArr);
return String.valueOf(sArr).equals(String.valueOf(tArr));
}
}
/*
Second version
*/
public class Solution {
public boolean isAnagram(String s, String t) {
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
char[] sArr = s.toCharArray();
char[] tArr = t.toCharArray();
for (Character c : sArr) {
if (hm.containsKey(c)) {
hm.put(c, hm.get(c) + 1);
} else {
hm.put(c, 1);
}
}
for (Character c : tArr) {
if (hm.containsKey(c)) {
hm.put(c, hm.get(c) - 1);
} else {
return false;
}
}
for (Integer value : hm.values()) {
if (value != 0) {
return false;
}
}
return true;
}
}