需求
描述
給定兩個字符串,求他們的最長公共子序列,其中子序列是可以不連續的。
輸入
abcfbc abfcab
programming contest
abcd mnp
輸出
4
2
0
分析
使用動態規劃,我們定義maxLen[i][j]
爲左字符串從頭開始的連續i
個字符與右字符串從頭開始的連續j
個字符的最大公共子序列,然後可以得到邊界及狀態轉移方程。
代碼
#include <iostream>
#include <cstring>
using namespace std;
char s1[1000];
char s2[1000];
int maxLen[1000][1000];
int main() {
// freopen("f:\\data.txt", "r", stdin);
while (cin >> s1 >> s2) {
//邊界狀態 arr[i][0],arr[0][j]都設爲0
int i, j, len1 = strlen(s1), len2 = strlen(s2);
for (i = 1; i <= len1; i++) maxLen[i][0] = 0;
for (j = 1; j <= len2; j++) maxLen[0][j] = 0;
//根據狀態轉移方程計算其它位置狀態
for (i = 1; i <= len1; i++)
for (j = 1; j <= len2; j++)
if (s1[i - 1] == s2[j - 1])
maxLen[i][j] = maxLen[i - 1][j - 1] + 1;
else
maxLen[i][j] = max(maxLen[i - 1][j], maxLen[i][j - 1]);
//輸出最後位置的狀態,即爲最大值
cout << maxLen[len1][len2] << endl;
}
return 0;
}