1650005688(1).png
    思路:

    1. 排序之后相等
    2. 字符数量相等
    1. package com.algorithm.demo.searchsorts;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. /**
    5. * @Author leijs
    6. * @date 2022/4/15
    7. */
    8. public class Demo1 {
    9. public static void main(String[] args) {
    10. String str1 = "nacos";
    11. String str2 = "cosna";
    12. System.out.println(isAnagram(str1, str2));
    13. }
    14. private static boolean isAnagram(String str1, String str2) {
    15. if (str1.length() != str2.length()) {
    16. return false;
    17. }
    18. Map<Character, Integer> map1 = new HashMap<>();
    19. for (Character ch : str1.toCharArray()) {
    20. if (map1.containsKey(ch)) {
    21. Integer total = map1.get(ch);
    22. map1.put(ch, total + 1);
    23. } else {
    24. map1.put(ch, 1);
    25. }
    26. }
    27. Map<Character, Integer> map2 = new HashMap<>();
    28. for (Character ch : str2.toCharArray()) {
    29. if (map2.containsKey(ch)) {
    30. Integer total = map2.get(ch);
    31. map2.put(ch, total + 1);
    32. } else {
    33. map2.put(ch, 1);
    34. }
    35. }
    36. if (map1.size() != map2.size()) {
    37. return false;
    38. }
    39. for (Character ch : map1.keySet()) {
    40. Integer f1 = map1.get(ch);
    41. Integer f2 = map2.get(ch);
    42. if (f2 == null || !f1.equals(f2)) {
    43. return false;
    44. }
    45. }
    46. return true;
    47. }
    48. }