![](https://i-blog.csdnimg.cn/blog_migrate/7803461fc054a548753afd84a120c8ab.png)
方法一:排序
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
char[] chS = s.toCharArray();
char[] chT = t.toCharArray();
Arrays.sort(chS);
Arrays.sort(chT);
return Arrays.equals(chS, chT);
}
}
方法二:计数
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] counter = new int[26];
for (char ch : s.toCharArray()) {
counter[ch - 'a']++;
}
for (char ch : t.toCharArray()) {
counter[ch - 'a']--;
}
for (int count : counter) {
if (count != 0) {
return false;
}
}
return true;
}
}
方法三:哈希表(可以解决进阶Unicode问题)
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> table = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) + 1);
}
for (int i = 0; i < t.length(); i++) {
char ch = t.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) - 1);
if (table.get(ch) < 0) {
return false;
}
}
return true;
}
}