给定两个字符串,求解这两个字符串的最长公共子序列(Longest Common Sequence)。比如字符串1:BDCABA;字符串2:ABCBDAB
则这两个字符串的最长公共子序列长度为4,最长公共子序列是:BCBA, (不要求连续)
动态规划假设给定的两个字符串为strA, strB, 令二维数组c[i,j]表示子串"strA[0], strA[1]......strA[i-1]" 与子串"strB[0], strB[1]......strB[j-1]"的最长公共子序列的长度,即 i,j代表长度, 0=< i <=strA.len, , 0=< j <=strB.len。
1) c[i,j] = c[i-1, j-1] + 1, 若strA[i-1] == strB[j-1]
2) c[i,j] = max{ c[i-1, j] , c[i, j-1] } , 若strA[i-1] != strB[j-1] , 即不能像情况1一样直接将最后的字符同时砍掉
3) c[i,j] = 0 , 若i==0或 j==0
int solve(const string& strA, const string& strB) {
const int lenA = strA.length();
const int lenB = strB.length();
if (lenA < 1 || lenB < 1)
return 0;
vector<vector<int>> cache(lenA+1, vector<int>(lenB+1,0));
for (int subLenA = 1; subLenA <= lenA; ++subLenA) {
for (int subLenB = 1; subLenB <= lenB; ++subLenB) {
if (strA[subLenA - 1] == strB[subLenB - 1]) {
cache[subLenA][subLenB] = cache[subLenA-1][subLenB-1] +1;
}
else {
cache[subLenA][subLenB] =
std::max(cache[subLenA][subLenB - 1], cache[subLenA-1][subLenB]);
}
}
}
return cache[lenA][lenB];
}
int main() {
int lennn = solve("BDCABA", "ABCBDAB");
return 0;
}