두 개의 문자열이 주어지면 우리의 임무는 가장 긴 공통 하위 문자열을 인쇄하는 것입니다. SequenceMatcher.find_longest_match() 메소드를 사용하여 파이썬에서 문제를 해결할 것입니다.
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