解法一
检查第一个字符串是不是出现在第二个字符串中,如果可以检查到每一个字符,那么则乱序。由于Python字符串是不可变的,所以第一步是将第二个字符串转换成列表。再检查第一个字符串中每个字符是否存在于第二个列表里。
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 = pos2 + 1
if found:
alist[pos2] = None
else:
stillOK = False
pos1 = pos1 + 1
return stillOK
print(anagramSolution1('abcd','dcba')) #True
#测试结果
>>> print(anagramSolution('abcd','dcbea'))
True
>>> print(anagramSolution('abecd','dcba'))
False
S1中的每个字符在S2中最多进行N个字符的比较,算法复杂度O(n^2)
解法二:排序和比较
按照字母顺序从a到z排列字符串,如果两个字符串相同,那么互为乱序字符串。
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','adcb'))
True
>>> print(anagramSolution2('abdc','acb'))
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print(anagramSolution2('abdc','acb'))
File "C:/Users/y/Desktop/test.py", line 13, in anagramSolution2
if alist1[pos] == alist2[pos]:
IndexError: list index out of range
>>>