class Solution: def isAnagram(self, s: str, t: str) -> bool: record = [0] *26 for i in s:# 用哈希法( 哈希函数:ord(i)-ord('a') )将'a'映射为0 'b'映射为1..'z'映射为25 其它字母同理 record[ord(i)-ord('a')] += 1 #此处不用记住ASCII 用ord()计算即可 for i in t: record[ord(i)-ord('a')] -= 1 for i in range(len(record)): if record[i] != 0: #若record有一个字母(元素)不为0 则不是Anagram return False return True
注:此题也可用defaultdict来做
class Solution: def isAnagram(self, s: str, t: str) -> bool: from collections import defaultdict s_dict = defaultdict(int) t_dict = defaultdict(int) for x in s: s_dict[x] += 1 for x in t: t_dict[x] += 1 return s_dict == t_dict