This is the classic LCS problem. Since It is only requires your to print the maximum length, the code can is optimized to use only O (m) space (see here).
My accepted code is as follows.
1#include <iostream>2#include <string>3#include <vector>4 5 using namespacestd;6 7 intLCsstringSstringt) {8 intm = s.length (), n =t.length ();9vector<int> cur (m +1,0);Ten for(inti =1; I <= m; i++) { One if(S[i-1] = = t[0]) Cur[i] =1; A ElseCur[i] = cur[i-1]; - } - for(intj =1; J < N; J + +) { the intPre =0; - for(inti =1; I <= m; i++) { - inttemp =Cur[i]; - if(S[i-1] = = T[j]) Cur[i] = pre +1; + ElseCur[i] = max (Cur[i], cur[i-1]); -Pre =temp; + } A } at returnCur[m]; - } - - intMainvoid) { - strings, t; - while(Getline (CIN, s)) { in getline (CIN, T); -cout << LCS (S, t) <<Endl; to } + return 0; -}
Well , try this problem here and get Accepted :)
[UVa Online Judge] Longest Common subsequence