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 stillok
print(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 matches
print(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 stillOK
print(anagramSolution4('python','typhon'))
總結(jié)
從以上幾種解法可以看出,要想在時(shí)間上獲得最優(yōu)就需要犧牲空間存儲(chǔ),因此沒有絕對(duì)的最優(yōu)解,只有在一定的平衡下,才能找到一個(gè)問題相對(duì)穩(wěn)定的解決方案。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python啟動(dòng)應(yīng)用程序和終止應(yīng)用程序的方法
今天小編就為大家分享一篇python啟動(dòng)應(yīng)用程序和終止應(yīng)用程序的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06
使用Python快速提取PPT中的文本內(nèi)容的代碼示例
Python標(biāo)準(zhǔn)庫(kù)urllib2的一些使用細(xì)節(jié)總結(jié)
python 列表,數(shù)組,矩陣兩兩轉(zhuǎn)換tolist()的實(shí)例
python anaconda 安裝 環(huán)境變量 升級(jí) 以及特殊庫(kù)安裝的方法
使用numba對(duì)Python運(yùn)算加速的方法

