解題思路
dp[i][j][c] 表示兩字串前綴中的合法共同子序列、最後字母為 c 的最大長度。
先繼承跳過 S[i] 或 T[j] 的狀態;若兩個新字母同為 c,就從對角線所有最後字母不為 c 的狀態取最大再加一,也允許空序列起步。
每個合法序列最後一字要麼未用新位置,要麼同時用了兩個新位置,轉移涵蓋全部情況。只保存前一列。
時間 O(26|S||T|),空間 O(26|T|+|S|)。
Step-by-step animation
教學例子:S=AABCA,T=ABACA,先選共同的 A、B。
步驟 1 / 3
步驟 1
S=AABCA,T=ABACA,先選共同的 A、B。
A
B
- 狀態
- 2
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s, t;
cin >> s >> t;
int m = t.size();
vector<array<int, 26>> dp(m + 1);
for (char x : s) {
vector<array<int, 26>> nd(m + 1);
for (int j = 1; j <= m; j++) {
for (int c = 0; c < 26; c++)
nd[j][c] = max(dp[j][c], nd[j - 1][c]);
if (x == t[j - 1]) {
int c = x - 'A', best = 0;
for (int d = 0; d < 26; d++)
if (c != d)
best = max(best, dp[j - 1][d]);
nd[j][c] = max(nd[j][c], best + 1);
}
}
dp.swap(nd);
}
cout << *max_element(dp[m].begin(), dp[m].end()) << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。