算法刷题Day 57 回文子串+最长回文子序列

Day 57 动态规划

647. 回文子串

暴力解法

class Solution {
    bool isPalindromic(const string &s) {
        int i = 0, j = s.size() - 1;
        while (i < j) {
            if (s[i] != s[j]) {
                return false;
            }
            i++; j--;
        }

        return true;
    }

public:
    int countSubstrings(string s) {
        int sum = 0;
        for (int i = 0; i < s.size(); i++) {
            for (int len = 1; i + len <= s.size(); len++) {
                string tmp = s.substr(i, len);
                if (isPalindromic(tmp)) {
                    sum++;
                }
            }
        }

        return sum;
    }
};

动态规划

class Solution {
public:
    int countSubstrings(string s) {
        int len = s.size(), cnt = 0;
        vector<vector<bool>> dp(len, vector<bool>(len, false));

        for (int i = len - 1; i >= 0; i--)
        {
            for (int j = i; j < len; j++)
            {
                if (s[i] == s[j])
                {
                    if (j - i <= 1)
                    {
                        cnt++;
                        dp[i][j] = true;
                    }
                    else if (dp[i + 1][j - 1])
                    {
                        cnt++;
                        dp[i][j] = true;
                    }
                }
            }
        }

        return cnt;
    }
};

双指针

从当前位置往两边找

class Solution {
    int check(const string &s, int left, int right)
    {
        int cnt = 0;

        while (left >= 0 && right < s.size() && s[left] == s[right])
        {
            left--;
            right++;
            cnt++;
        }

        return cnt;
    }

public:
    int countSubstrings(string s) {
        int cnt = 0;

        for (int i = 0; i < s.size(); i++)
        {
            cnt += check(s, i, i);
            cnt += check(s, i, i + 1);
        }

        return cnt;
    }
};

516. 最长回文子序列

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        int len = s.size(), maxLen = 1;
        vector<vector<int>> dp(len, vector<int>(len, 0));
        for (int i = 0; i < len; i++)
        {
            dp[i][i] = 1;
        }

        for (int i = len - 1; i >= 0; i--)
        {
            for (int j = i + 1; j < len; 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]);
                }

                if (dp[i][j] > maxLen)
                {
                    maxLen = dp[i][j];
                }
            }
        }

        return maxLen;
    }
};

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