1、逐字检查法
代码展示
def bian_wei_ci(ls1,ls2):
alist=list(ls2)
pos1=0
result=True
#print(len(ls1))
if len(ls1)==len(ls2):
while pos1<len(ls1) and result:
pos2=0
found=False
while pos2<len(alist) and not found:
if ls1[pos1] == alist[pos2]:
found=True
else:
pos2=pos2+1
if found:
alist[pos2]=None
else:
result=False
break
pos1=pos1+1
return result
else:
result=False
return result
分析
问题规模:词中包含的字符个数n
主要部分在两重循环:外层循环遍历s1每个字符,将内层循环执行n次,而内层循环在s2中查找字符,每个字符的对比次数是1、2……n中的一个,各不相同,取平均为(n+1)/2
所以执行次数是n*(n+1)/2
所以数量级O(n的平方)
2、排序比较法
代码展示
def bian_wei_ci2(ls1,ls2):
list1=list(ls1)
list2=list(ls2)
list1.sort()
list2.sort()
result=True
pos=0
if len(list1)==len(list2):
while pos<len(list1) and result:
if list1[pos]==list2[pos]:
pos += 1
else:
result=False
return result
else:
result=False
return result
分析
乍一看这个方法只有一个循环,最多执行n次,数量级是O(n),但是循环前面的两次sort()并不是没有代价的,排序算法采用不同的解决方案其运行时间差不多是O(n的平方)或者O(nlogn),大过循环O(n)
所以本算法时间主导的步骤是排序步骤,本算法运行时间数量级等于排序过程的数量级O(nlogn)
计数比较法
代码展示
def bian_wei_ci3(ls1,ls2):
c1=[0]*26
c2=[0]*26
for i in range(len(ls1)):
pos=ord(ls1[i])-ord('a')
c1[pos]=c1[pos]+1
for i in range(len(ls2)):
pos=ord(ls2[i])-ord('a')
c2[pos]=c2[pos]+1
j=0
result=True
while j<26 and result:
if c1[j]==c2[j]:
j+=1
else:
result=False
return result
分析
计数比较算法中有3个循环迭代,但不像解法一那样存在嵌套循环
其总操作次数为2n+26,其数量级为O(n)
值得注意的是,本算法依赖于两个长度为26的计数器列表,来保存字符计数,这相比于前两个算法需要更多的存储空间。这种牺牲存储空间来换取运行时间,或者相反,这种在时间空间之间的取舍和权衡,在选择问题的解决过程中经常会出现。