1:问题描述

Given two strings s and t , write a function to determine if t is an anagram of s.

判断是不是异位词

2:最无聊的解决方案

```java // 用排序实现 // 时间复杂度 O(nlogn) // 空间复杂度 O(1) public static boolean isAnagram(String s, String t) { char[] sChar = s.toCharArray(); char[] tChar = t.toCharArray(); Arrays.sort(sChar); Arrays.sort(tChar); return String.valueOf(sChar).equals(String.valueOf(tChar)); }

  1. <a name="EcxZT"></a>
  2. ## 3:原生解题结果
  3. ```java
  4. // 哈希表
  5. // 时间复杂度 O(n)
  6. // 空间复杂度 O(1)
  7. public static boolean isAnagram(String s, String t) {
  8. Map<Character, Integer> map = new HashMap<>();
  9. for (char ch : s.toCharArray()) {
  10. map.put(ch, map.getOrDefault(ch, 0) + 1);
  11. }
  12. for (char ch : t.toCharArray()) {
  13. Integer count = map.get(ch);
  14. if (count == null) {
  15. return false;
  16. } else if (count > 1) {
  17. map.put(ch, count - 1);
  18. } else {
  19. map.remove(ch);
  20. }
  21. }
  22. return map.isEmpty();
  23. }
  1. // 计数器
  2. public static boolean isAnagram(String s, String t) {
  3. if (s.length() != t.length()) {
  4. return false;
  5. }
  6. int[] counter = new int[26];
  7. for (int i = 0; i < s.length(); i++) {
  8. counter[s.charAt(i) - 'a']++;
  9. counter[t.charAt(i) - 'a']--;
  10. }
  11. for (int count : counter) {
  12. if (count != 0) {
  13. return false;
  14. }
  15. }
  16. return true;
  17. }

4:解题思路

因为比较是不是异位词,就比较字母出现的次数就好了,所以哈希表或计数器一样的思路实现

5:Go语言实现

  1. func isAnagram(s string, t string) bool {
  2. if len(s) != len(t) {
  3. return false
  4. }
  5. strMap := make(map[string]int)
  6. for i := 0; i < len(s); i++ {
  7. strMap[string(s[i])]++
  8. }
  9. for j := 0; j < len(t); j++ {
  10. strMap[string(t[j])]--
  11. }
  12. for _, v := range strMap {
  13. if v != 0 {
  14. return false
  15. }
  16. }
  17. return true
  18. }