代码随想录算法训练营Day57 | 647. 回文子串,516.最长回文子序列,动态规划总结篇

647. 回文子串

文章链接  |  题目链接  |  视频链接

C++解法

class Solution {
public:
    int countSubstrings(string s) {
        vector> dp (s.size(), vector(s.size(), false));
        int result = 0;
        for (int i = s.size()-1; i >= 0; i--){
            for (int j = i; j < s.size(); j++){
                if (s[i] == s[j] && (j - i <= 1 || dp[i+1][j-1])){
                    result++;
                    dp[i][j] = true;
                }
            }
        }
        return result;
    }
};

Python解法

class Solution:
    def countSubstrings(self, s: str) -> int:
        dp = [[False] * len(s) for _ in range(len(s))]
        result = 0
        for i in range(len(s)-1, -1, -1):
            for j in range(i, len(s)):
                if s[i] == s[j] and (j - i <= 1 or dp[i+1][j-1]):
                    result += 1
                    dp[i][j] = True
        return result

516.最长回文子序列

文章链接  |  题目链接  |  视频链接

C++解法

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        vector> dp (s.size(), vector(s.size(), 0));
        for (int i = 0; i < s.size(); i++) dp[i][i] = 1;
        for (int i = s.size()-1; i >= 0; i--){
            for (int j = i+1; j < s.size(); 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[0][s.size() - 1];
    }
};

Python解法

class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        dp = [[0] * len(s) for _ in range(len(s))]
        for i in range(len(s)):
            dp[i][i] = 1
        for i in range(len(s)-1, -1, -1):
            for j in range(i+1, len(s)):
                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[0][-1]

动态规划总结篇

文章链接

你可能感兴趣的:(代码随想录刷题训练营,算法,动态规划)