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 次浏览

开启你的 职业

完成课程后获得证书

开始
广告
© . All rights reserved.