基本數據結構之變位詞三種解法

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'))
相關文章
相關標籤/搜索