Print the longest common substring | C ++ implementation to 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 ; move diagonally up to previous cell ; required longest common substring ; Driver program to test above function
#include <iostream> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE using namespace std ; void printLCSubStr ( char * X , char * Y , int m , int n ) { int LCSuff [ m + 1 ] [ n + 1 ] ; int len = 0 ; int row , col ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { 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 ) { cout << " No ▁ Common ▁ Substring " ; return ; } char * resultStr = ( char * ) malloc ( ( len + 1 ) * sizeof ( char ) ) ; while ( LCSuff [ row ] [ col ] != 0 ) { row -- ; col -- ; } cout << resultStr ; } int main ( ) { char X [ ] = " OldSite : GeeksforGeeks . org " ; char Y [ ] = " NewSite : GeeksQuiz . com " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; printLCSubStr ( X , Y , m , n ) ; return 0 ; }