具体所使用的方法可参考Turing的《python数据结构与算法分析》或搜索其他资料文章。
清点法
def anagramSolution(a,b):
if len(a)!=len(b):
return False
else:
a = a.lower()
b = b.lower()
bb = list(b)
lenth = len(a)
pos1 = 0
flag1 = True
while pos1 < lenth and flag1:
pos2 = 0
flag2 = False
while pos2 < lenth and not flag2:
if a[pos1] == bb[pos2]:
flag2 = True
bb[pos2] = None
else:
pos2 = pos2 + 1
if not flag2:
flag1 = False
pos1 = pos1+1
return flag1
str1 = str(input('please input the first word:'))
str2 = str(input('please input the second word:'))
if anagramSolution(str1, str2):
print('anagram')
else:
print('not anagram')
结果截图:
排序法
def anagramSolution2 (a,b):
#第一个if判断两个字符串是否为0
if len(a)!=len(b):
return False
else:
#把字符串里面的大写字母转为小写字母
a = a.lower()
b = b.lower()
aa = list(a)
bb = list(b)
aa.sort()
bb.sort()
lenth = len(a)
flag1 = True
pos = 0
while pos<lenth and flag1:
if aa[pos] != bb[pos]:
flag1 = False
pos = pos + 1
return flag1
str1 = str(input('please enter the first string: '))
str2 = str(input('please enter the second string: '))
print('anagram is %s' % anagramSolution2(str1, str2))
结果截图:
计数法
def anagramSolution3(a,b):
if len(a)!=len(b):
return False
else:
a = a.lower()
b = b.lower()
numa = [0]*26
numb = [0]*26
lenth = len(a)
for i in range(lenth):
pos = ord(a[i]) - ord('a')
numa[pos] = numa[pos] + 1
for i in range(lenth):
pos = ord(b[i]) - ord('a')
numb[pos] = numb[pos] + 1
pos2 = 0
flag = True
while pos2<26 and flag:
if numa[pos2] != numb[pos2]:
flag = False
pos2 = pos2+1
return flag
str1 = str(input('please enter the first string: '))
str2 = str(input('please enter the second string: '))
print('anagram is %s' % anagramSolution3(str1, str2))
结果截图:
其中,清点法时间复杂度为O(n^2)。
排序法时间复杂度取决于排序算法,如果用时间复杂度最低的排序算法,其时间复杂度为O(nlogn)。
计数法是以空间换取时间的方法,时间复杂度为O(n)。