最长回文子串(动态规划)c++

题目描述:给你一个字符串 s,找到 s 中最长的回文子串。

递推式:

class Solution {
public:
    string longestPalindrome(string s) {
        int len=s.size();
        if(len<2)
            return s;
        bool dp[len][len];//布尔型,dp[i][j]表示从i到j是否构成回文
       int max_count=1;//最大字串的长度
       int start=0;//最长字串的起始位置
        for(int j=0;j<len;j++)
        {
            for(int i=0;i<j;i++)
            {
                if(s[i]!=s[j])
                    dp[i][j]=false;
                else if((j-i)<3)//(j-1)-(i+1)+1<2表示dp[i][j]的最大字串长度为1
                    dp[i][j]=true;
                else
                {
                    dp[i][j]=dp[i+1][j-1];
                }
                if((j-i+1)>max_count&&dp[i][j])
                 {
                    max_count=j-i+1;
                    start=i;
                 }   
            
            }
  
        }     
        return s.substr(start,max_count);//截取字符串
    }
};

 

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务