题目

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

  1. 输入: s = "anagram", t = "nagaram"
  2. 输出: true

示例 2:

  1. 输入: s = "rat", t = "car"
  2. 输出: false

说明:
你可以假设字符串只包含小写字母。

解答

  1. #
  2. # @lc app=leetcode.cn id=242 lang=python3
  3. #
  4. # [242] 有效的字母异位词
  5. #
  6. # @lc code=start
  7. class Solution:
  8. def isAnagram(self, s: str, t: str) -> bool:
  9. statS = [0 for x in range(26)]
  10. statT = [0 for x in range(26)]
  11. lenS = len(s)
  12. lenT = len(t)
  13. i = 0
  14. while i < lenS:
  15. index = ord(s[i]) - ord('a')
  16. statS[index] = statS[index] + 1
  17. i = i + 1
  18. i = 0
  19. while i < lenT:
  20. index = ord(t[i]) - ord('a')
  21. statT[index] = statT[index] + 1
  22. i = i + 1
  23. i = 0
  24. print(statS, statT, "======")
  25. while i < 26:
  26. if statS[i] != statT[i]:
  27. return False
  28. i = i + 1
  29. return True
  30. print(Solution().isAnagram("rac", "car"))
  31. # @lc code=end

Note

桶排序
声明两个26长度的列表statS和statT,分别遍历传入的两个参数s和t,按a-0,b-1的规律写入statS和statT,
最后分别比较这两条列表每个值是否相同

image.png