1.堆排序,比较字符串顺序是否一致
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
def sift(lis,low,high):
temp=lis[low]
i=low
j=2*i+1
while j<=high:
if j+1<=high and lis[j+1]>=lis[j]:
j+=1
if lis[j]>temp:
lis[i]=lis[j]
i=j
j=2*i+1
else:
break
lis[i]=temp
def heap_sort(lis,lis2):
l=len(lis)
for i in range((l-2)//2,-1,-1):
sift(lis,i,l-1)
sift(lis2,i,l-1)
for j in range(l):
lis[0],lis[l-1-j]=lis[l-1-j],lis[0]
sift(lis,0,l-1-j-1)
lis2[0],lis2[l-1-j]=lis2[l-1-j],lis2[0]
sift(lis2,0,l-1-j-1)
if lis[l-1-j]!=lis2[l-1-j]:
return False
return True
s=list(s)
t=list(t)
if len(s)!=len(t):
return False
return heap_sort(s,t)
2.直接用sort排序后比较
3.比较每一个字母的出现次数再结合哈希表
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
hasp_map={}
for i in range(len(s)):
if hasp_map.get(s[i]) is None:
hasp_map[s[i]]=1
else:
hasp_map[s[i]]+=1
for i in range(len(t)):
if hasp_map.get(t[i]) is not None:
hasp_map[t[i]]-=1
if hasp_map[t[i]]==0:
del hasp_map[t[i]]
else:
return False
return hasp_map=={}
4.建议一个长度位26的列表,列表用来记录出现次数,最后判断列表是否相等,该方法与法3原理是一致的