Print the longest common substring | function to find and print the longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Create a table to store lengths of longest common suffixes of substrings . Note that LCSuff [ i ] [ j ] contains length of longest common suffix of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] . The first row and first column entries have no logical meaning , they are used only for simplicity of program ; To store length of the longest common substring ; To store the index of the cell which contains the maximum value . This cell 's index helps in building  up the longest common substring from right to left. ; Following steps build LCSuff [ m + 1 ] [ n + 1 ] in bottom up fashion . ; if true , then no common substring exists ; allocate space for the longest common substring ; traverse up diagonally form the ( row , col ) cell until LCSuff [ row ] [ col ] != 0 ; resultStr = X [ row - 1 ] + resultStr ; or Y [ col - 1 ] ; move diagonally up to previous cell ; required longest common substring ; Driver program to test above function
function printLCSubStr ( X , Y , m , n ) { let LCSuff = new Array ( m + 1 ) ; let len = 0 ; let row = 0 , col = 0 ; for ( let i = 0 ; i <= m ; i ++ ) { LCSuff [ i ] = Array ( n + 1 ) ; for ( let j = 0 ; j <= n ; j ++ ) { LCSuff [ i ] [ j ] = 0 ; if ( i == 0 j == 0 ) LCSuff [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) { LCSuff [ i ] [ j ] = LCSuff [ i - 1 ] [ j - 1 ] + 1 ; if ( len < LCSuff [ i ] [ j ] ) { len = LCSuff [ i ] [ j ] ; row = i ; col = j ; } } else LCSuff [ i ] [ j ] = 0 ; } } if ( len == 0 ) { document . write ( " " ) ; return ; } let resultStr = " " ; while ( LCSuff [ row ] [ col ] != 0 ) { -- len ; row -- ; col -- ; } document . write ( resultStr ) ; } let X = " " ; let Y = " " ; let m = X . length ; let n = Y . length ; printLCSubStr ( X , Y , m , n ) ;