Python 中的 SequenceMatcher 適用於最長公共子串。


給定兩個字串,我們的任務是列印最長的公共子串。我們將使用 SequenceMatcher.find_longest_match () 方法用 Python 來解決這個問題。

Difflib.SequenceMatcher 類是一個靈活的類,用於比較任意型別的序列對,只要序列元素可進行雜湊處理即可。

find_longest_match(a, x, b, y)

查詢 a[a:x] 和 b[b:y] 中最長的匹配塊。

示例

Input:  str1 = "pythonprogramming", 
        str2 = "pro"
Output: pro

演算法

Step 1: Enter two string.
Step 2: initialize SequenceMatcher object with the input string.
Step 3: find the match of longest sub-string output.
Step 4: print longest substring.

示例程式碼

# Python program to find Longest Common Sub-string 
from difflib import SequenceMatcher 
def matchsubstring(m,n): 
   seqMatch = SequenceMatcher(None,m,n) 
   match = seqMatch.find_longest_match(0, len(m), 0, len(n)) 
   if (match.size!=0): 
      print ("Common Substring ::>",m[match.a: match.a + match.size])  
   else: 
      print ('No longest common sub-string found') 
# Driver program 
if __name__ == "__main__": 
   X = input("Enter first String ")
   Y = input("Enter second String ")
   matchsubstring(X,Y) 

輸出

Enter first String pythonprogramming
Enter second String pro
Common Substring ::> pro

更新於: 2019-07-30

912 次瀏覽

開啟你的 職業

完成課程後獲得證書

開始
廣告