heart & earth python & typhon 写一个bool函数判断两个词是否为变位词
#解法1:逐字检查
!由于在Python中字符串其中字符无法改变,先将单词赋值到列表中
解法1运行时间数量级为O(n^2)
def anagram1kenn(s1, s2):
alist = list(s1)
blist = list(s2)
if len(alist) != len(blist):
return False
if alist == blist:
return False
for i in alist:
flag1 = False
for n, j in enumerate(blist):
if (i == j) and (flag1 is False):
blist[n] = None
flag1 = True
if flag1:
pass
else:
return False
return True
#解法2:排序比较
将两个字符串都按照字母进行排序后比较
解法2主导过程为排序,数量级为O(n^2)或O(n logn)
def anagram2kenn(s1, s2):
alist = list(s1)
blist = list(s2)
if len(alist) != len(blist):
return False
if alist == blist:
return False
alist.sort()
blist.sort()
if alist == blist:
return True
else:
return False