代码随想录算法训练营第59天|647. 回文子串、516.最长回文子序列

647. 回文子串

https://leetcode.cn/problems/palindromic-substrings/

一开始我做的:

class Solution {
public:
    bool isSub(string &s, int left, int right) {
        while(left < right) {
            if (s[left] != s[right]) return false;
            left++;
            right--;
        }
        return true;
    }
    int countSubstrings(string s) {
        vector dp(s.length() + 1, 0);
        for (int i = 1; i <= s.length(); i++) {
            dp[i] = dp[i - 1];
            for (int j = 1; j <= i; j++) {
                if (isSub(s, j - 1, i - 1)) {
                    dp[i] += 1;
                }
            }
        }
        return dp.back();
    }
};

更换思路后:

class Solution {
public:
    int countSubstrings(string s) {
        //dp[i][j] i到j是否是回文串
        //dp[i][j] = s[i] == s[j] && dp[i + 1][j - 1]
        int result = 0;
        vector> dp(s.length(), vector(s.length(), false));
        for (int i = s.length() - 1; i >= 0; i--) {
            for (int j = i; j < s.length(); j++) {
                if (s[i] == s[j]) {
                    if (j - i <= 1) {
                        result++;
                        dp[i][j] = true;
                    }
                    else if (dp[i + 1][j - 1]) {
                        result++;
                        dp[i][j] = true;
                    }
                }
                
            }
        }
        return result;
    }
};

516.最长回文子序列

https://leetcode.cn/problems/longest-palindromic-subsequence/

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        //dp[i][j] 从i到j中间最长的回文子序列
        vector> dp(s.length(), vector(s.length(), 0));
        for (int i = 0; i < s.length(); i++) {
            dp[i][i] = 1;
        }
        for (int i = s.length() - 1; i >= 0; i--) {
            for (int j = i + 1; j < s.length(); j++) {
                if (s[i] == s[j]) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                }
                else {
                    dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp.front().back();
    }
};

你可能感兴趣的:(算法)