242. 有效的字母異位詞
問題
給定兩個字符串 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 僅包含小寫字母
進階: 如果輸入字符串包含 unicode 字符怎么辦?你能否調整你的解法來應對這種情況?
解決
字典比較
class Solution:def isAnagram(self, s: str, t: str) -> bool:s_dict=defaultdict(int)t_dict=defaultdict(int)for x in s:s_dict[x]+=1for x in t:t_dict[x]+=1return s_dict==t_dict