数据结构与算法(Python版)—课堂实例—变位词

数据结构与算法(Python版)

题目

写一个bool函数,以两个词作为参数,返回这两个词是否变位词。(”变位词“是指两个词之间存在组成字母的重新排列关系,如heart和earth,python和typhon)(假设输入的单词都是小写并且长度相同)

解答
解法1:逐字检查法(时间复杂度O(n^2))

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

# 解法1:逐字检查法
def anagramSolution1(s1, s2):
    aList2 = list(s2)
    pos1 = 0
    stillOK = True
    while pos1 < len(s1) and stillOK:
        pos2 = 0
        found = False
        while pos2 < len(aList2) and not found:
            if s1[pos1] == aList2[pos2]:
                aList2[pos2] = None
                found = True
            else:
                pos2 += 1
        if not found:
            stillOK = False
        pos1 += 1
    return stillOK
解法2:排序比较法(时间复杂度O(nlogn))

将两个字符串排好序,再逐个比较对应位置上的字符是否一致,如果相同就是变位词,如果有任何不同就不是变位词。

def anagramSolution2(s1, s2):
    alist1 = list(s1)
    alist2 = list(s2)

    alist1.sort()
    alist2.sort()
    pos = 0
    is_match = True
    while pos < len(s1) and is_match:
        if alist1[pos] == alist2[pos]:
            pos += 1
        else:
            is_match = False
    return is_match
解法3:计数比较法(时间复杂度O(n))

对比两个词中每个字母出现的次数,如果26个字母,每个字母出现的次数相同的话,则这两个字符串一定是变位词。

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

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

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

    return stillOK
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值