最长公共子序列
参考
http://blog.youkuaiyun.com/zhongkeli/article/details/8847694 ---没有加 strA[lenA-1]==strB[lenB-1]
,有误
如最后一个7行6列是 4,6行5列是3 ,但是strA[7]是B ,strB[6]是A 所以不对,
要加strA[lenA-1]==strB[lenB-1] 判断
#include
#include
#include
#include
using namespace std;
string lcs(string strA, string strB) {
int lenA = strA.size();
int lenB = strB.size();
// f[i][j] 存储的是strA中0 ~ i-1 与strB中0~j-1的公共子序列长度 ,i=0或j=0 表示strA或strB没有字符时的最长公共子序列,所以都是0
vector
> f(lenA+1,vector
(lenB+1,0)); for (int i = 0; i < lenA; i++) { for (int j = 0; j < lenB; j++) { if (strA[i] == strB[j]) f[i + 1][j + 1] = f[i][j] + 1; // i,j 的状态存储在 f[i+1][j+1] else f[i + 1][j + 1] = max(f[i][j + 1], f[i + 1][j]); } } int maxlen = f[lenA][lenB]; string commStr(maxlen,'a'); while (maxlen) { //一定 要有 strA[lenA - 1] == strB[lenB - 1] if (strA[lenA - 1] == strB[lenB - 1] && f[lenA][lenB] == f[lenA - 1][lenB - 1] + 1) { commStr[--maxlen] = strA[--lenA]; --lenB; } else if (f[lenA - 1][lenB] >= f[lenA][lenB - 1]) { --lenA; } else --lenB; } return commStr; } int main(int argc, char const *argv[]) { string A = "abcd"; string B = "bd"; cout << lcs(A, B); return 0; }