【Python】(二)第二個字符串是否只是第一個的重新排列?

問題描述

我們的目標是寫一個函數(shù),它將兩個字符串做參數(shù)并返回布爾值。如果第二個字符串只是第一個的重新排列,那么返回True,否則返回False。例如,'apple' 和 'paple' 就返回True。'java' 和 'aavj' 也是。
我們假設(shè)兩個字符串具有相等的長度,并且他們由 26 個小寫英文字母組成。

逐個字符比較法

首先我們考慮逐個將第一個字符串中的字符與第二個字符進行比較,判斷包含關(guān)系,如果全部包含在第二個字符中

def method_1(str_1, str_2):
    str_2 = list(str_2)
    pos_1 = 0
    flag_same = True
    while pos_1<len(str_1) and flag_same:
        try:
            pos_2 = str_2.index(str_1[pos_1]) ##查找操作
            str_2.pop(pos_2)
        except:
            flag_same = False
        pos_1 += 1
    return flag_same

def main():
    ###前三個正確結(jié)果為true,后兩個正確結(jié)果為false。
    List1 = ['apple','pear','reading','swimming','commic']
    List2 = ['paple','aerp','ndrgiea','mwgswini','imiucm']
    
    ###逐個比較法
    for i in range(len(List1)):
        print("Sum method 1 -- %s and %s -- Result %s ."%(List1[i], List2[i], method_1(List1[i], List2[i])))

    print("----------------------------------------------")

if __name__ == "__main__":
    main()

運行結(jié)果為:

Sum method 1 -- apple and paple -- Result True .
Sum method 1 -- pear and aerp -- Result True .
Sum method 1 -- reading and ndrgiea -- Result True .
Sum method 1 -- swimming and mwgswini -- Result False .
Sum method 1 -- commic and imiucm -- Result False .
----------------------------------------------

結(jié)果是正確的,查找操作的時間復(fù)雜度假設(shè)為O(n),則總的時間復(fù)雜度為O(n^2)。

先排序后比較的方法

兩個字符串如果能夠返回True,那么它們在字符級別各自排序后應(yīng)該是相同的字符串。

def method_1(str_1, str_2):
    str_2 = list(str_2)
    pos_1 = 0
    flag_same = True
    while pos_1<len(str_1) and flag_same:
        try:
            pos_2 = str_2.index(str_1[pos_1]) ##查找操作
            str_2.pop(pos_2)
        except:
            flag_same = False
        pos_1 += 1
    return flag_same

def method_2(str_1, str_2):
    str_1 = list(str_1)
    str_1.sort() ##排序操作
    str_2 = list(str_2)
    str_2.sort() ##排序操作
    for i in range(len(str_1)):
        if str_1[i] != str_2[i]:
            return False
    return True

def main():
    ###前三個正確結(jié)果為true,后兩個正確結(jié)果為false。
    List1 = ['apple','pear','reading','swimming','commic']
    List2 = ['paple','aerp','ndrgiea','mwgswini','imiucm']
    
    ###逐個比較法
    for i in range(len(List1)):
        print("Sum method 1 -- %s and %s -- Result %s ."%(List1[i], List2[i], method_1(List1[i], List2[i])))

    print("----------------------------------------------")
    
    ###排序后比較法
    for i in range(len(List1)):
        print("Sum method 2 -- %s and %s -- Result %s ."%(List1[i], List2[i], method_2(List1[i], List2[i])))

    print("----------------------------------------------")

if __name__ == "__main__":
    main()

運行結(jié)果如下:

Sum method 1 -- apple and paple -- Result True .
Sum method 1 -- pear and aerp -- Result True .
Sum method 1 -- reading and ndrgiea -- Result True .
Sum method 1 -- swimming and mwgswini -- Result False .
Sum method 1 -- commic and imiucm -- Result False .
----------------------------------------------
Sum method 2 -- apple and paple -- Result True .
Sum method 2 -- pear and aerp -- Result True .
Sum method 2 -- reading and ndrgiea -- Result True .
Sum method 2 -- swimming and mwgswini -- Result False .
Sum method 2 -- commic and imiucm -- Result False .
----------------------------------------------

排序操作的時間復(fù)雜度通常為O(n2)或O(nlogn),因而總的時間復(fù)雜度也是O(n2)或O(nlogn)。這與第一種方法的時間復(fù)雜度基本相當(dāng)。

先計數(shù)后比較法

我們以26個計數(shù)單位來計數(shù)兩個字符串中字符出現(xiàn)的次數(shù),比較是否相同。


def method_1(str_1, str_2):
    str_2 = list(str_2)
    pos_1 = 0
    flag_same = True
    while pos_1<len(str_1) and flag_same:
        try:
            pos_2 = str_2.index(str_1[pos_1]) ##查找操作
            str_2.pop(pos_2)
        except:
            flag_same = False
        pos_1 += 1
    return flag_same

def method_2(str_1, str_2):
    str_1 = list(str_1)
    str_1.sort() ##排序操作
    str_2 = list(str_2)
    str_2.sort() ##排序操作
    for i in range(len(str_1)):
        if str_1[i] != str_2[i]:
            return False
    return True

def method_3(str_1, str_2):
    count_list = [0]*26 ##計數(shù)用數(shù)組
    for x in list(str_1):
        count_list[ord(x)-ord('a')] += 1
    for x in list(str_2):
        count_list[ord(x)-ord('a')] -= 1
    for x in count_list:
        if x != 0:
            return False
    return True

def main():
    ###前三個正確結(jié)果為true,后兩個正確結(jié)果為false。
    List1 = ['apple','pear','reading','swimming','commic']
    List2 = ['paple','aerp','ndrgiea','mwgswini','imiucm']
    
    ###逐個比較法
    for i in range(len(List1)):
        print("Sum method 1 -- %s and %s -- Result %s ."%(List1[i], List2[i], method_1(List1[i], List2[i])))

    print("----------------------------------------------")
    
    ###排序后比較法
    for i in range(len(List1)):
        print("Sum method 2 -- %s and %s -- Result %s ."%(List1[i], List2[i], method_2(List1[i], List2[i])))

    print("----------------------------------------------")
    
    ###計數(shù)后比較法
    for i in range(len(List1)):
        print("Sum method 3 -- %s and %s -- Result %s ."%(List1[i], List2[i], method_3(List1[i], List2[i])))

if __name__ == "__main__":
    main()

運行結(jié)果如下:

Sum method 1 -- apple and paple -- Result True .
Sum method 1 -- pear and aerp -- Result True .
Sum method 1 -- reading and ndrgiea -- Result True .
Sum method 1 -- swimming and mwgswini -- Result False .
Sum method 1 -- commic and imiucm -- Result False .
----------------------------------------------
Sum method 2 -- apple and paple -- Result True .
Sum method 2 -- pear and aerp -- Result True .
Sum method 2 -- reading and ndrgiea -- Result True .
Sum method 2 -- swimming and mwgswini -- Result False .
Sum method 2 -- commic and imiucm -- Result False .
----------------------------------------------
Sum method 3 -- apple and paple -- Result True .
Sum method 3 -- pear and aerp -- Result True .
Sum method 3 -- reading and ndrgiea -- Result True .
Sum method 3 -- swimming and mwgswini -- Result False .
Sum method 3 -- commic and imiucm -- Result False .

在O(n)的時間復(fù)雜度下就可以完成運算,這種空間換時間的方法是更為有效的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 首先總結(jié)以下Java和C、C++中的一般控制臺輸入方式,方便以后的編程題: java鍵盤輸入 java讀文件(會自...
    androidjp閱讀 2,383評論 0 16
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • 西湖文化廣場 什么時候來的杭州? 9月末10月初。 什么時候想來的杭州? 很久之前就想。 為什么想來杭州? 恩.....
    那點鼻事閱讀 346評論 0 0
  • 已經(jīng)坐上回家的大巴了,雨下的特別大,天冷的讓人直打哆嗦。出門前雖是看了天氣預(yù)報,卻高估了自己個御寒能力,出發(fā)那...
    咸魚愛蝦米閱讀 322評論 0 0

友情鏈接更多精彩內(nèi)容