Valid Anagram
判断两个字符串是否为异位词,意思是判断两个字符串有相同数量的字母。
Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
有三种解法:
第一种最简单:
先对s和t排序,再对比是否相等
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s) == sorted(t)
第二种使用哈希表计数:
def isAnagram(self, s, t):
dict1 = {}
dict2 = {}
for i in s:
if i in dict1:
dict1[i] += 1
else:dict1[i] = 1
for j in t:
if j in dict2:
dict2[j] += 1
else:dict2[j] = 1
遍历一个字符串,看字母在不在哈希表中,在的话就加1,不在就设置为1.
第三种使用列表实现哈希表
def isAnagram(self, s, t):
dic1,dic2 = [0]*26,[0]*26
for i in s:
dic1[ord(i) - ord('a')] += 1
for i in t:
dic2[ord(i) - ord('a')] += 1
return dic1 == dic2
先初始化列表,再用字母的ASCII码减去a的ASCII码,等到的列表index += 1,26字母对应0-25的索引值。