变位词算法
一、变位词的定义
变位词:两个词之间存在组成字母的重新排列关系。
比如heart和earth,python和typhon
二、识别两个词是否为变位词
为简单起见,假设参与判断的两个词仅由小写字母构成,而且长度相等。
1.逐字比较
def anagramSolution1(s1,s2):
'''逐字检查'''
alist=list(s2). ##字符串是不可修改的
pos1=0
stillOK=True
while pos1<len(s1) and stillOK:
pos2=0
found=False
while pos2<len(alist) and not found:
if s1[pos1]==alist[pos2]:
found=True
else:
pos2+=1
if found:
alist[pos2]=None
else:
stillOK=False
pos1+=1
return stillOK
时间复杂度为 O ( n 2 ) \ O(n^2) O(n2)
2.排序比较
def anagarmSolution2(s1,s2):
'''排序比较'''
alist1=list(s1)
alist2=list(s2)
alist1.sort() #在原地址排序
alist2.sort()
pos=0
matched=True
while pos<len(s1) and matched:
if alist1[pos]==alist2[pos]:
pos+=1
else:
matched=False
return matched
或者
def bianweici2(s1,s2):
alist1=list(s1)
alist2=list(s2)
alist1.sort()
alist2.sort()
if alist1==alist2:
return True
else:
return False
时间复杂度为 O ( n log n ) \ O(n\log n) O(nlogn)
3.计数比较
def anagarmSolution3(s1,s2):
'''计数比较'''
c1=[0]*26
c2=[0]*26
for i in range(len(s1)):
pos=ord(s1[i])-ord('a')
c1[pos]+=1
for j in range(len(s2)):
pos=ord(s2[j])-ord('a')
c2[pos]+=1
j=0
stillOK=True
while j<26 and stillOK:
if c1[j]==c2[j]:
j+=1
else:
stillOK=False
return stillOK
或者
def bianweici3(s1,s2):
c1=[0]*26
c2=[0]*26
for i in range(len(s1)):
pos=ord(s1[i])-ord('a') #ord()返回值是对应的十进制整数
c1[pos]+=1
for j in range(len(s2)):
pos=ord(s2[j])-ord('a')
c2[pos]+=1
if c1==c2:
return True
else:
return False
时间复杂度为 O ( n ) \ O( n) O(n)