LCS formed by consecutive segments of at least length K | Returns the length of the longest common subsequence with a minimum of length of K consecutive segments ; length of strings ; declare the lcs and cnt array ; iterate from i = 1 to n and j = 1 to j = m ; stores the maximum of lcs [ i - 1 ] [ j ] and lcs [ i ] [ j - 1 ] ; when both the characters are equal of s1 and s2 ; when length of common segment is more than k , then update lcs answer by adding that segment to the answer ; formulate for all length of segments to get the longest subsequence with consecutive Common Segment of length of min k length ; update lcs value by adding segment length ; Driver code
def longestSubsequenceCommonSegment ( k , s1 , s2 ) : NEW_LINE INDENT n = len ( s1 ) NEW_LINE m = len ( s2 ) NEW_LINE lcs = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE cnt = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT lcs [ i ] [ j ] = max ( lcs [ i - 1 ] [ j ] , lcs [ i ] [ j - 1 ] ) NEW_LINE if ( s1 [ i - 1 ] == s2 [ j - 1 ] ) : NEW_LINE INDENT cnt [ i ] [ j ] = cnt [ i - 1 ] [ j - 1 ] + 1 ; NEW_LINE DEDENT if ( cnt [ i ] [ j ] >= k ) : NEW_LINE INDENT for a in range ( k , cnt [ i ] [ j ] + 1 ) : NEW_LINE INDENT lcs [ i ] [ j ] = max ( lcs [ i ] [ j ] , lcs [ i - a ] [ j - a ] + a ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return lcs [ n ] [ m ] NEW_LINE DEDENT k = 4 NEW_LINE s1 = " aggasdfa " NEW_LINE s2 = " aggajasdfa " NEW_LINE print ( longestSubsequenceCommonSegment ( k , s1 , s2 ) ) NEW_LINE