Longest Common Substring ( Space optimized DP solution ) | Function to find longest common substring . ; Find length of both the strings . ; Variable to store length of longest common substring . ; Matrix to store result of two consecutive rows at a time . ; Variable to represent which row of matrix is current row . ; For a particular value of i and j , len [ currRow ] [ j ] stores length of longest common substring in string X [ 0. . i ] and Y [ 0. . j ] . ; Make current row as previous row and previous row as new current row . ; Driver Code
< ? php function LCSubStr ( $ X , $ Y ) { $ m = strlen ( $ X ) ; $ n = strlen ( $ Y ) ; $ result = 0 ; $ len = array ( array ( ) , array ( ) , ) ; $ currRow = 0 ; for ( $ i = 0 ; $ i <= $ m ; $ i ++ ) { for ( $ j = 0 ; $ j <= $ n ; $ j ++ ) { if ( $ i == 0 $ j == 0 ) { $ len [ $ currRow ] [ $ j ] = 0 ; } else if ( $ X [ $ i - 1 ] == $ Y [ $ j - 1 ] ) { $ len [ $ currRow ] [ $ j ] = $ len [ 1 - $ currRow ] [ $ j - 1 ] + 1 ; $ result = max ( $ result , $ len [ $ currRow ] [ $ j ] ) ; } else { $ len [ $ currRow ] [ $ j ] = 0 ; } } $ currRow = 1 - $ currRow ; } return $ result ; } $ X = " GeeksforGeeks " ; $ Y = " GeeksQuiz " ; print ( LCSubStr ( $ X , $ Y ) ) ; ? >