变位词问题

题目描述

所谓“变位词”是指两个词之间存在组成字母的重新排列关系

如:heart和earth,python和typhon

为了简单起见,假设参与判断的两个词仅由小写字母构成,而且长度相同

参考实现1

def anagramSolution(s1, s2):
    alist1 = list(s1)  # 字符串转列表
    alist2 = list(s2)

    alist1.sort()  # 排序
    alist2.sort()
    pos = 0  # 列表起始位置索引
    flag = True
    while pos < len(s1) and flag:  # 遍历
        if alist1[pos] == alist2[pos]:  # 依次比较两个列表的元素
            pos += 1
        else:
            flag = False
    return flag


word1 = 'xiaohua'
word2 = 'huaxiao'

print(anagramSolution(word1, word2))     #True
print(anagramSolution(word1, word2 + 'c')) #False

说明:粗看上去,本算法只有一个循环,最多执行n次,数量级是O(n),但循环前面但两个sort并不是无代价的,会发现排序算法采用不同的解决方案,其运算时间数量级差不多是O(n^2)或者O(n log n),大过循环的O(n),所以本算法时间主导的步骤是排序步骤

参考实现2

def anagramSolution1(s1,s2):
    #准备两个列表
    a1 = [0] * 26
    a2 = [0] * 26
    for i in range(len(s1)):
        '''print(s1[i] + ' --- ' )
        print( ord(s1[i]))
        print(ord('a'))'''
        pos = ord(s1[i]) - ord('a') #ord返回字母的Unicode值,这里通过字母和指定值的差值作为标记进行对比
        a1[pos] += 1
    for i in range(len(s2)):
        pos = ord(s2[i]) - ord('a')
        a2[pos] += 1
    j = 0
    flag = True
    print(a1)
    print(a2)
    while j < 26 and flag:

        if a1[j] == a2[j]:
            j += 1
        else:
            flag = False
    return flag


word1 = 'xiaohua'
word2 = 'huaxiao'

print(anagramSolution1(word1, word2))     #True
print(anagramSolution1(word1, word2 + 'c')) #False
分析:计数比较算法中有3个循环迭代,但不像解法1那样存在嵌套循环,前两个循环用于对字符串进行计数,操作次数等于字符串长度n,第3个循环用于计数器比较,操作次数总是26次,所以总操作次数T(n)=2n+26,其数量级为O(n)
posted @ 2023-05-24 21:57  晓枫的春天  阅读(11)  评论(0编辑  收藏  举报