def isAnagram(s, t):
# 排序比较
if len(s) != len(t):
return False
sList = list(s)
sList.sort()
tList = list(t)
tList.sort()
for i in range(len(s)):
if sList[i] == tList[i]:
continue
else:
return False
return True
列表化后删除
def isAnagram(s, t):
#列表化后删除
if len(s) != len(t):
return False
sList = list(s)
for word in t:
try:
sList.remove(word)
except ValueError as e:
return False
return True
利用字典统计
def isAnagram(s, t):
dict1={}
dict2={}
for i in s:
if i not in dict1:
dict1[i] = 1
else:
dict1[i] += 1
for i in t:
if i not in dict2:
dict2[i]=1
else:
dict2[i]+=1
if len(dict1)!=len(dict2):
return False
else:
for key,value in dict1.items():
if key not in dict2:
return False
else:
if value == dict2[key]:
continue
else:
return False
return True