力扣--242有效的字母异位词
作者:互联网
题目
python 代码
排序比较
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
标签:dict1,return,dict2,--,len,else,力扣,242,False 来源: https://blog.csdn.net/weixin_48994268/article/details/117414140