Fork me on GitHub

赏月斋源码共享计划 第六期 变位词判断

本文用三种算法实现了变位词判断问题。

所谓“变位词”是指两个词之间存在组成字母的重新排列关系,如:heart和earth,python和typhon

假设参与判断的词仅由大写字母组成。

解题目标:写一个bool函数,以两个词作为参数,返回这两个词是否变位词。

 

输入:两个字符串s1和s2

返回:一个bool变量。

 

# coding=utf8
def judgeStr_1(s1, s2):
    # 先排序,再对比
    list1 = list(s1)
    list2 = list(s2)
    
    list1.sort()
    list2.sort()

    # if list1 == list2:  # 这样判断也可以
    #     return True
    # else:
    #     return False
    
    if len(list1) != len(list2):
        return False

    for i in range(len(list1)):
        if list1[i] == list2[i]:
            continue
        else:
            return False
    return True


def judgeStr_2(s1, s2):         # 打钩法(两层循环,在s2里边便利找s1的当前值,找到打标记found,未找到found=false),注意s1每循环一次都要将found置为false
    l1 = list(s1)
    l2 = list(s2)

    OK = True
    if len(l1) != len(l2):
        OK = False
    k = 0
    found = False
    for i in range(len(l1)):
        found = False
        for j in range(len(l2)):
            if l1[i] == l2[j]:
                found = True
                k = j
                break
        if found == True:
            l2[k] = None
        else:
            OK = False    
    
    return OK


def judgeStr_3(s1, s2):   # 空间换时间:26个字母对应一个长为26的数组,数组上的数字表示对应字母在s1,s2中出现了几次,如果出现次数一样,则是变位次
    cnt1 = [0] * 26
    cnt2 = [0] * 26
    l1 = list(s1)
    l2 = list(s2)
    if len(l1) != len(l2):
        return False

    # python中获取ASCII值的函数 ,ord=ordinal(序数的,顺序的)
    for i in range(len(l1)):
        cnt1[ord(l1[i])-ord('A')] += 1
    for i in range(len(l2)):
        cnt2[ord(l2[i])-ord('A')] += 1
    OK = True
    for i in range(len(cnt2)):
        if cnt1[i] == cnt2[i]:
            continue
        return False
    
    return True


s1 = "ABCDEFG"
s2 = "BACFEGD"
result1 = judgeStr_1(s1, s2)
result2 = judgeStr_2(s1, s2)
result3 = judgeStr_3(s1, s2)
print(result1, result2, result3)

  

 

posted @ 2020-10-29 18:54  stardsd  阅读(171)  评论(0编辑  收藏  举报