基本数据结构之变位词三种解法

def anagramSolution1(s1, s2):
    """
    变位词第一种解法:O(n^2)
    :param s1:
    :param s2:
    :return:
    """
    alist = list(s2)  # s2字符串转换为列表
    pos1 = 0
    stillOK = True
    while pos1 < len(s1) and stillOK:  # 循环s1的每个字符
        pos2  = 0
        found = False
        while pos2 < len(alist) and not found:
            if s1[pos1] == alist[pos2]:  # 与s2元素逐个对比
                found = True
            else:
                pos2 += 1
        if found:
            alist[pos2] = None  # 找到,打钩
        else:
            stillOK = False  # 未找到,失败
        pos1 += 1
    return stillOK


print(anagramSolution1(‘python‘, ‘typhon‘))

def anagramSolution2(s1, s2):
    """
    变位词第二种解法:O(nlogn)
    :param s1:
    :param s2:
    :return:
    """
    alist = list(s1)
    blist = list(s2)
    alist.sort()  # 分别排序
    blist.sort()
    matches = True
    pos1 = 0
    while pos1 < len(alist) and matches:
        if alist[pos1] == blist[pos1]:  # 一一对比
            matches = True
        else:
            matches = False
        pos1 += 1
    return matches


print(anagramSolution2(‘abcd‘, ‘dcba‘))


def anagramSolution3(s1, s2):
    """
    变位词第三种解法,计数比较变位词:O(n)
    :param s1:
    :param s2:
    :return:
    """
    c1 = [0] * 26
    c2 = [0] * 26
    for i in range(len(s1)):
        pos = ord(s1[i]) - ord(‘a‘)  # 分别计数
        c1[pos] += 1
    for i in range(len(s2)):
        pos = ord(s1[i]) - ord(‘a‘)
        c2[pos] += 1
    j = 0
    stillOK = True
    while j < 26 and stillOK:  # 计数器比较
        if c1[j] == c2[j]:
            j+=1
        else:
            stillOK = False
    return stillOK

print(anagramSolution3(‘apple‘, ‘pleap‘))

相关推荐