检查字符串每个元素是否匹配
def anagramSolution(s1,s2):
alist = list(s2)
pos1 = 0
stillok = True
while pos1 < len(s1) and stillok: #外层循环负责遍历s1中每个元素,stillok表示s2中存在,若不存在,则结束循环
pos2 = 0
found = False #默认在s2中未找到
while pos2 < len(alist) and not found:
if s1[pos1] == alist[pos2]: #找到,found置为True,结束内层循环
found = True
else: #未找到,则查找s2中下一个
pos2 = pos2 + 1
if found: #找到,将s2中pos2位置的字母置为None
alist[pos2] = None
else: #内层循环结束未找到,结束整个循环,字符串不匹配
stillok = False
pos1 = pos1 + 1 #内层循环结束,且找到,则pos1+1,找s1中的下个字符
return stillok
print(anagramSolution("python","tpyhon"))
外层循环n次,内部查找次数为1,2,3…n中的某个数,
时间复杂度为:
1+2+…+n = n*(n+1)/2
def anagramSolution(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 += 1
else:
matches = False
return matches
print(anagramSolution("pyh","hpu"))
先对字符串排序,然后逐一比较。
import operator
def anagramSolution(s1,s2):
aDict1 = {}
aDict2 = {}
for i in s1:
aDict1[i] = aDict1.get(i,1) + 1
for j in s2:
aDict2[j] = aDict2.get(j,1) + 1
sortedClassCount1 = sorted(aDict1.items(), key=operator.itemgetter(0), reverse=True)
sortedClassCount2 = sorted(aDict2.items(), key=operator.itemgetter(0), reverse=True)
return sortedClassCount1==sortedClassCount2
print(anagramSolution("put","upt"))
返回字典对比值也是一样,将s1,s2中每个元素转化为字典形式,并予以计数对比