LCS ( Longest Common Subsequence ) of three strings | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] and Z [ 0. . o - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] [ o + 1 ] in bottom up fashion . Note that L [ i ] [ j ] [ k ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] and Z [ 0. . ... k - 1 ] ; L [ m ] [ n ] [ o ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] and Z [ 0. . o - 1 ] ; Driver program to test above function
def lcsOf3 ( X , Y , Z , m , n , o ) : NEW_LINE INDENT L = [ [ [ 0 for i in range ( o + 1 ) ] for j in range ( n + 1 ) ] for k in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT for k in range ( o + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 or k == 0 ) : NEW_LINE INDENT L [ i ] [ j ] [ k ] = 0 NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ j - 1 ] and X [ i - 1 ] == Z [ k - 1 ] ) : NEW_LINE INDENT L [ i ] [ j ] [ k ] = L [ i - 1 ] [ j - 1 ] [ k - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] [ k ] = max ( max ( L [ i - 1 ] [ j ] [ k ] , L [ i ] [ j - 1 ] [ k ] ) , L [ i ] [ j ] [ k - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return L [ m ] [ n ] [ o ] NEW_LINE DEDENT X = ' AGGT12' NEW_LINE Y = '12TXAYB ' NEW_LINE Z = '12XBA ' NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE o = len ( Z ) NEW_LINE print ( ' Length ▁ of ▁ LCS ▁ is ' , lcsOf3 ( X , Y , Z , m , n , o ) ) NEW_LINE