lc1771 由子序列構造的最長迴文串的長度

chenfy27發表於2024-03-21

給出兩個字串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;
    }
};

相關文章