题目:给定两个字符串 ,编写一个函数来判断它们是不是一组变位词(字母异位词)
解法1:逐字检查-程序代码
解题思路:将一个字符串拆开,逐个在另一个字符中是否存在,存在就打钩,打勾标记,由于字符串位不可变序列,需要先复制到列表中。
def anagramSolution1(s1,s2):
alist = list(s2) #复制s2到列表
pos1 = 0
stillok=True
while pos1 < len(s1) and stillok: #循环s1的每个字符
pos2 = 0
found = False
while pos2 < len(alist) and not found:
if s1[pos1] == alist[pos2]:#在与s2逐个对比
found =True
else:
pos2 = pos2 + 1
if found:
alist[pos2] = None #找到打勾
else:
stillok = False #未找到,失败
pos1 = pos1 + 1
return stillok
#测试用例
print(anagramSolution1('abc','cba'))
解法2:排序比较(相对简单好理解)
解题思路:将字符串逐个转变成列表,再进行排序,这样的话如果是变位数,这两个列表里的字符以及位置都相等,再进行比对就可以了
def anagramSolution2(s1,s2):
alist1 = list(s1) #转化为列表
alist2 = list(s2)
alist1.sort() #分别排序
alist2.sort()
pos=0
matches = True
while pos < len(s1) and matches:
if alist1[pos] == alist2[pos]: #逐个排序
pos = pos + 1
else:
matches = False
return matches
#测试用例
print(anagramSolution2('abc','cba'))
解法3:计数比较-程序代码
解题思路:创造计数器,记录两个字符串里字母出现的次数(因为变位词的字母出现的次数是一样的,正是利用这一特点),在对两个字符的计数器进行比对,相同及相等
def anagramSolution3(s1,s2):
c1 = [0] * 26 #创建有26个0的列表
c2 = [0] * 26
#分别都计数
for i in range(len(s1)): #ord函数返回对应的Unicode码,与之相对的是chr()函数
pos = ord(s1[i]) - ord('a') #ord函数返回字符的ASCII码
c1[pos] = c1[pos] +1
for i in range(len(s2)):
pos = ord(s1[i]) - ord('a')
c2[pos] = c2[pos] +1
j = 0
stillok = True
#计数器比较
while j < 26 and stillok:
if c1[j] == c2[j]:
j = j +1
else:
stillok = False
return stillok
#测试用例
print(anagramSolution2('abc','cba'))
解法4:暴力解法
解题思路:穷尽所有可能组合,将s1中出现的字符进行全排列,再查看s2是否出现再全排列列表中。如果将n个字符进行全排列,其所有可能的字符串个数为n!。