A Space Optimized Solution of LCS | Space optimized C ++ implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Find lengths of two strings ; Binary index , used to index current row and previous row . ; Compute current binary index ; Last filled entry contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lcs ( string & X , string & Y ) { int m = X . length ( ) , n = Y . length ( ) ; int L [ 2 ] [ n + 1 ] ; bool bi ; for ( int i = 0 ; i <= m ; i ++ ) { bi = i & 1 ; for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ bi ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ bi ] [ j ] = L [ 1 - bi ] [ j - 1 ] + 1 ; else L [ bi ] [ j ] = max ( L [ 1 - bi ] [ j ] , L [ bi ] [ j - 1 ] ) ; } } return L [ bi ] [ n ] ; } int main ( ) { string X = " AGGTAB " ; string Y = " GXTXAYB " ; printf ( " Length ▁ of ▁ LCS ▁ is ▁ % d STRNEWLINE " , lcs ( X , Y ) ) ; return 0 ; }