示例 1
输入: s = "anagram", t = "nagaram"
输出: true
示例 2
输入: s = "rat", t = "car"
输出: false
一个重要的前提“假设两个字符串只包含小写字母”,小写字母一共也就 26 个,因此:
class Solution: def isAnagram(self, s: str, t: str) -> bool: dic1, dic2 = {}, {} for item in s: dic1[item] = dic1.get(item, 0) + 1 for item in t: dic2[item] = dic2.get(item, 0) + 1 return dic1 == dic2 # return sorted(s) == sorted(t) 或 solution = Solution() print(solution.isAnagram(s="anagram", t="nagaram")) # True
LeetCode 第 242 题:给定两个字符串 s 和 t,编写一个函数来判断 t 是否是 s 的字母异位词
原文:https://www.cnblogs.com/zhaoyingjie/p/13996849.html