给定两个字符串,我们的任务是打印最长的公共子字符串。我们将使用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