面试常考题 最长回文串与回文序列

最长回文子序列

题目链接 https://leetcode.com/problems/longest-palindromic-subsequence/

给定一个字符串s,找到其中最长的回文子序列。可以假设s的最大长度为1000。
最长回文子序列和上一题最长回文子串的区别是,子串是字符串中连续的一个序列,而子序列是字符串中保持相对位置的字符序列,例如,"bbbb"可以使字符串"bbbab"的子序列但不是子串。

动态规划: dp[i][j] = dp[i+1][j-1] + 2 if s.charAt(i) == s.charAt(j) otherwise, dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1])

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

一个串中回文串的个数

题目链接: https://leetcode.com/problems/palindromic-substrings/

给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。

具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。

class Solution {
public:
    int countSubstrings(string s) {
        int len = s.size();
        if(len <= 1)
            return len;
        int res = 0;
        for(int i=0; i<len; i++) {
            check(s, i, i, res);
            check(s, i, i+1, res);
        }
        return res;
    }
    
    void check(string s, int i, int j, int &res) {
        while(true) {
            if(i>=0 && j < s.size() && s[i] == s[j]) {
                res ++;
                i--, j++;
            } else 
                break;
        }
        return ;
    }
};
posted @ 2019-07-31 10:13  Draymonder  阅读(377)  评论(0编辑  收藏  举报