python實現對變位詞的判斷方法
Python實現對變位詞的判斷,供大家參考,具體內容如下
什么是變位詞呢?即兩個單詞都是由相同的字母組成,而各自的字母順序不同,譬如python和typhon,heart和earth。
變位詞的判斷
既然我們知道了變位詞的定義,那么接下來就是實現對兩個單詞是否是變位詞進行判斷了,以下展示變位詞判斷的幾種解法:
1、逐字檢查
將單詞1中的所有字符逐個到單詞2中檢查是否存在對應字符,存在就標記實現:將詞2中存在的對應字符設置None,由于字符串是不可變類型,需要先將詞2字符復制到列表中時間復雜度:O(n^2)
def anagramSolution1(s1,s2): 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: # 與s2的字符逐個對比 if s1[pos1] == alist[pos2]: found = True else: pos2 = pos2 + 1 if found: alist[pos2] = None # 找到對應,標記 else: stillok = False # 沒有找到,失敗 pos1 = pos1 + 1 return stillokprint(anagramSolution1(’python’,’typhon’))
2、排序比較
實現:將兩個字符串都按照字母順序重新排序,再逐個比較字符是否相同時間復雜度:O(n log n)
def anagramSolution2(s1,s2): alist1 = list(s1) alist2 = list(s2) alist1.sort() # 對字符串進行順序排序 alist2.sort() pos = 0 matches = True while pos < len(s1) and matches: if alist1[pos] == alist2[pos]: # 逐個對比 pos = pos + 1 else: matches = False return matchesprint(anagramSolution2(’python’,’typhon’))
3、窮盡法
將s1的字符進行全排列,再查看s2中是否有對應的排列時間復雜度為n的階乘,不適合作為解決方案
4、計數比較
將兩個字符串的字符出現的次數分別統計,進行比較,看相應字母出現的次數是否一樣時間復雜度:O(n),從時間復雜度角度而言是最優解
def anagramSolution4(s1,s2): c1 = [0] * 26 c2 = [0] * 26 for i in range(len(s1)): pos = ord(s1[i]) - ord(’a’) # ord函數返回字符的Unicode編碼,此語句可以將字符串中的字母轉換成0-25的數字 c1[pos] = c1[pos] + 1 # 實現計數器 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: # 計數器比較 if c1[j] == c2[j]: j = j + 1 else: stillOK = False return stillOKprint(anagramSolution4(’python’,’typhon’))
總結
從以上幾種解法可以看出,要想在時間上獲得最優就需要犧牲空間存儲,因此沒有絕對的最優解,只有在一定的平衡下,才能找到一個問題相對穩定的解決方案。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: