469 字
2 分钟
变位词问题的解法及其时间复杂度分析
检查两个词是否为变位词
比如python和typthon、heart和earth
def anagramSolution1(s1,s2): stillOK = True alist = list(s2) pos1 = 0 while pos1 < len(s1) and stillOK: pos2 = 0 found = False while pos2 < len(list(s2)) 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逐字检查 算法复杂度分析
外层循环遍历s1为n,内层循环为 1~n其中的一个数
所以最终执行次数为1+2+…+n = n(n+1)/2 = n^2
因此O(n^2)
def anagramSolution2(s1,s2): ''' 最简 return sort(s1) == sort(s1) ''' alist1 = list(s1) alist2 = list(s2)
alist1.sort() #sort()的时间复杂度为O(n log n) alist2.sort() stillOK = True pos = 0 while pos < len(s1) and stillOK: # O(n) if alist1[pos] == alist2[pos]: pos = pos + 1 else: stillOK = False return stillOK排序比较 算法复杂度分析 取最大为O(n log n)
def anagramSolution3(s1,s2): ''' 以下是伪代码 将s1进行全排列之后将s2与每一种可能性进行比较 若成功则输出True ''' stillOK = True return stillOK暴力法 算法复杂度分析
总执行次数为 n*(n-1)*…21 = n!
O(n!)非常大 O(n!) > O(2^n)
print(anagramSolution3('python','typhon'))
def anagramSolution4(s1,s2): stillOK = True c1 = [0] * 26 c2 = [0] * 26
for i in range(len(s1)): pos = ord(s1[i]) - ord('a') #ord函数用来返回一个字符的unicode编码 c1[pos] = c1[pos] + 1 #c1[pos]处的值+1 for i in range(len(s2)): pos = ord(s2[i]) - ord('a') #减去之后正好对应0~25的索引 c2[pos] = c2[pos] + 1
j = 0 while j < 26 and stillOK: #遍历每一个计数器 if c1[j] == c2[j]: j = j + 1 else: stillOK = False return stillOK计数比较 算法复杂度分析 总执行次数为T(n) = 2n + 26 所以为O(n)
扩展:使用哈希表
def anagramSolution4(s1, s2): count1 = {} count2 = {}
for char in s1: count1[char] = count1.get(char, 0) + 1 #会储存为{'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1} for char in s2: count2[char] = count2.get(char, 0) + 1
return count1 == count2 #时间复杂度也为O(n) 分享
如果这篇文章对你有帮助,欢迎分享给更多人!
变位词问题的解法及其时间复杂度分析
https://chaojixin.ren/posts/变位词/ 部分信息可能已经过时









