python實(shí)現(xiàn)對(duì)變位詞的判斷方法
Python實(shí)現(xiàn)對(duì)變位詞的判斷,供大家參考,具體內(nèi)容如下
什么是變位詞呢?即兩個(gè)單詞都是由相同的字母組成,而各自的字母順序不同,譬如python和typhon,heart和earth。
變位詞的判斷
既然我們知道了變位詞的定義,那么接下來就是實(shí)現(xiàn)對(duì)兩個(gè)單詞是否是變位詞進(jìn)行判斷了,以下展示變位詞判斷的幾種解法:
1、逐字檢查
將單詞1中的所有字符逐個(gè)到單詞2中檢查是否存在對(duì)應(yīng)字符,存在就標(biāo)記實(shí)現(xiàn):將詞2中存在的對(duì)應(yīng)字符設(shè)置None,由于字符串是不可變類型,需要先將詞2字符復(fù)制到列表中時(shí)間復(fù)雜度:O(n^2)
def anagramSolution1(s1,s2): alist = list(s2) # 復(fù)制s2 pos1 = 0 stillok = True while pos1 < len(s1) and stillok: # 循環(huán)s1的所有字符 pos2 = 0 found = False # 初始化標(biāo)識(shí)符 while pos2 < len(alist) and not found: # 與s2的字符逐個(gè)對(duì)比 if s1[pos1] == alist[pos2]: found = True else: pos2 = pos2 + 1 if found: alist[pos2] = None # 找到對(duì)應(yīng),標(biāo)記 else: stillok = False # 沒有找到,失敗 pos1 = pos1 + 1 return stillokprint(anagramSolution1(’python’,’typhon’))
2、排序比較
實(shí)現(xiàn):將兩個(gè)字符串都按照字母順序重新排序,再逐個(gè)比較字符是否相同時(shí)間復(fù)雜度:O(n log n)
def anagramSolution2(s1,s2): alist1 = list(s1) alist2 = list(s2) alist1.sort() # 對(duì)字符串進(jìn)行順序排序 alist2.sort() pos = 0 matches = True while pos < len(s1) and matches: if alist1[pos] == alist2[pos]: # 逐個(gè)對(duì)比 pos = pos + 1 else: matches = False return matchesprint(anagramSolution2(’python’,’typhon’))
3、窮盡法
將s1的字符進(jìn)行全排列,再查看s2中是否有對(duì)應(yīng)的排列時(shí)間復(fù)雜度為n的階乘,不適合作為解決方案
4、計(jì)數(shù)比較
將兩個(gè)字符串的字符出現(xiàn)的次數(shù)分別統(tǒng)計(jì),進(jìn)行比較,看相應(yīng)字母出現(xiàn)的次數(shù)是否一樣時(shí)間復(fù)雜度:O(n),從時(shí)間復(fù)雜度角度而言是最優(yōu)解
def anagramSolution4(s1,s2): c1 = [0] * 26 c2 = [0] * 26 for i in range(len(s1)): pos = ord(s1[i]) - ord(’a’) # ord函數(shù)返回字符的Unicode編碼,此語句可以將字符串中的字母轉(zhuǎn)換成0-25的數(shù)字 c1[pos] = c1[pos] + 1 # 實(shí)現(xiàn)計(jì)數(shù)器 for i in range(len(s2)): pos = ord(s2[i]) - ord(’a’) c2[pos] = c2[pos] + 1 j = 0 stillOK = True while j < 26 and stillOK: # 計(jì)數(shù)器比較 if c1[j] == c2[j]: j = j + 1 else: stillOK = False return stillOKprint(anagramSolution4(’python’,’typhon’))
總結(jié)
從以上幾種解法可以看出,要想在時(shí)間上獲得最優(yōu)就需要犧牲空間存儲(chǔ),因此沒有絕對(duì)的最優(yōu)解,只有在一定的平衡下,才能找到一個(gè)問題相對(duì)穩(wěn)定的解決方案。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. XHTML 1.0:標(biāo)記新的開端5. ASP基礎(chǔ)知識(shí)VBScript基本元素講解6. 利用CSS3新特性創(chuàng)建透明邊框三角7. XML入門的常見問題(四)8. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼9. 詳解CSS偽元素的妙用單標(biāo)簽之美10. HTML5 Canvas繪制圖形從入門到精通
