思路:
- 排序之后相等
- 字符数量相等
package com.algorithm.demo.searchsorts;
import java.util.HashMap;
import java.util.Map;
/**
* @Author leijs
* @date 2022/4/15
*/
public class Demo1 {
public static void main(String[] args) {
String str1 = "nacos";
String str2 = "cosna";
System.out.println(isAnagram(str1, str2));
}
private static boolean isAnagram(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
Map<Character, Integer> map1 = new HashMap<>();
for (Character ch : str1.toCharArray()) {
if (map1.containsKey(ch)) {
Integer total = map1.get(ch);
map1.put(ch, total + 1);
} else {
map1.put(ch, 1);
}
}
Map<Character, Integer> map2 = new HashMap<>();
for (Character ch : str2.toCharArray()) {
if (map2.containsKey(ch)) {
Integer total = map2.get(ch);
map2.put(ch, total + 1);
} else {
map2.put(ch, 1);
}
}
if (map1.size() != map2.size()) {
return false;
}
for (Character ch : map1.keySet()) {
Integer f1 = map1.get(ch);
Integer f2 = map2.get(ch);
if (f2 == null || !f1.equals(f2)) {
return false;
}
}
return true;
}
}