【每日算法】宝,你今天练算法了吗?

问题描述

“变位词”是指两个词之间存在组成字母的 重新排列关系 如:heart和earth,python和typhon 为了简单起见,假设参与判断的两个词仅由小写 字母构成,而且长度相等(Python实现)

解法1:逐字检查

将词1中的字符逐个到词2中检查是否存在,存在就打勾标记(防止重复检查),如果每个字符都能找到,则两个词是变位词,只要有一个字符找不到,就不是变位词

def anagramSolution(s1, s2):
    alist = list(s2)
    pos1 = 0
    stilOK = True
    while pos1 < len(s1) and stilOK:
        pos2 = 0
        found = False
        while pos2 < len(alist) and not found:
            if s1[pos1] == alist[pos2]:
                found = True
            else:
                pos2 += 1

        if found:
            alist[pos2] = None
        else:
            stilOK = False
        pos1 = pos1 + 1
    return stilOK


print(anagramSolution('python', 'thonay'))

解法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('python', 'thonay'))

解法3:计数比较

解题思路:对比两个词中每个字母出现的 次数,如果26个字母出现的次数都相同的话,这两个字符串就一定是变位词

def anagramSolution3(s1, s2):
    c1 = [0] * 26
    c2 = [0] * 26

    for i in range(len(s1)):
        pos = ord(s1[i])-ord('a')
        c1[pos] = c1[pos] + 1

    for i in range(len(s2)):
        pos = ord(s2[i])-ord('a')
        c2[pos] = c2[pos] + 1

    j = 0
    stilOk = True

    while j < 26 and stilOk:
        if c1[j] == c2[j]:
            j = j + 1
        else:
            stilOk = False

    return stilOk

大家可以看下这三种方式,分别的时间复杂度是多少?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值