1. 程式人生 > 程式設計 >python實現對變位詞的判斷方法

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 stillok
print(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 matches
print(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 stillOK
print(anagramSolution4('python','typhon'))

總結

從以上幾種解法可以看出,要想在時間上獲得最優就需要犧牲空間儲存,因此沒有絕對的最優解,只有在一定的平衡下,才能找到一個問題相對穩定的解決方案。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。