242. 有效的字母异位词
原始题目链接:https://leetcode.cn/problems/valid-anagram/
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
示例 1:
输入: s = “anagram”, t = “nagaram”
输出: true
示例 2:
输入: s = “rat”, t = “car”
输出: false
提示:
1 <= s.length, t.length <= 5 * 104
s 和 t 仅包含小写字母
解题思路:
统计字符串的字符个数,存放在字典中,再判断字典是否一样即可。
代码实现:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
import collections
a = collections.defaultdict(int)
b = collections.defaultdict(int)
for c in s:
a[c] += 1
for c in t:
b[c] += 1
if a == b:
return True
return False