给出两个字符串word1和word2,需要从word1和word2分别选出某个非空子序列s1和s2,要求连接s1与s2后得到回文串,求该回文串的最大长度。
word1和word2长度在[1,1000]内。
区间dp,将word1与word2拼接起来,转换成求单个字符串的的最长回文子序列问题,为了保证s1和s2非空,枚举word1和word2中每个位置i和j,如果word1[i]=word2[j],则该答案有效,需要统计。
class Solution {
public:
int dp[2005][2005];
int longestPalindrome(string word1, string word2) {
string s = word1 + word2;
int n = s.size();
for (int d = 1; d <= n; d++) {
for (int i = 0; i+d-1 < n; i++) {
int j = i+d-1;
if (d == 1) {
dp[i][j] = 1;
} else if (d == 2) {
dp[i][j] = s[i] == s[j] ? 2 : 1;
} else if (s[i] == s[j]) {
dp[i][j] = 2 + dp[i+1][j-1];
} else {
dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
}
}
}
int n1 = word1.size();
int n2 = word2.size();
int ans = 0;
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
if (word1[i] == word2[j])
ans = max(ans, dp[i][n1+j]);
}
}
return ans;
}
};
标签:由子,lc1771,int,s2,s1,word1,word2,回文
From: https://www.cnblogs.com/chenfy27/p/18088247