演算法分析2.4-亂序字串檢查

來源:互聯網
上載者:User

標籤:例子   pos   轉變   2.4   條件   亂序   else   dss   ppp   

來源:https://legacy.gitbook.com/book/xidianwlc/python-data-structrue-and-algrothms/details

參考學習,代碼改進 

2.4.一個亂序字串檢查的例子
#python#查詢s2中是否包含s1中的的字母是否相同def anagramSolution1(s1,s2):    print(type(s1))    print(type(s2))    alist=list(s2) #將元組轉變為列表    pos1=0    stillOk=True    while pos1<len(s1) and stillOk:        pos2=0        found=False        while pos2<len(alist) and not found:  #當存在字母相同時,跳出迴圈 或不存在相同時跳出迴圈            if s1[pos1]==alist[pos2] and pos2==len(s1)-pos1-1:  #加上pos2==len(s1)-pos1-1為迴文判斷                found=True                    #判定條件            else:                pos2=pos2+1        if found:            alist[pos2]=None        else:            stillOk=False        pos1=pos1+1            return stillOkprint(anagramSolution1(‘abcd‘,‘abdc‘))print(anagramSolution1(‘abcd‘,‘d‘))#查詢s2中是否包含s1中的的字母是否相同,排序後篩選def anagramSolution2(s1,s2):    alist1=list(set(s1))  #set()去重    alist2=list(set(s2))    alist1.sort()    alist2.sort()    print(alist1,alist2)    pos=0    matches=True    while pos<len(alist1) and matches: #len(alist1)計算alist1的長度,當s1=s2否者會報錯        if alist1[pos]==alist2[pos]:            pos=pos+1        else:            matches=False    return matchesprint(anagramSolution2(‘abcdss‘,‘abcdddwdss‘))print(anagramSolution2(‘asbscde‘,‘asbscde‘))#計數和比較,s1 s2字母相同,且個數相同,排序不同c1=[0]*26   def anagramSolution4(s1,s2):    c1=[0]*26    c2=[0]*26    for i in range(len(s1)):  #計算每個字母出現的次數        pos=ord(s1[i])-ord(‘a‘) #ord()返回對應的 ASCII 數值,或者 Unicode 數值 計算與a數值大小        c1[pos]=c1[pos]+1    for i in range(len(s2)):        pos=ord(s2[i])-ord(‘a‘)        c2[pos]=c2[pos]+1    print(c1,c2)    j=0    stillOK=True    while j<26 and stillOK:  #比較字母出現個數數量是夠相同        if c1[j]==c2[j]:            j=j+1        else:            stillOK=False    return stillOKprint(anagramSolution4(‘appleppp‘,‘pleapppp‘))

  

 

演算法分析2.4-亂序字串檢查

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.