码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode5 最长回文子串

时间:2019-11-20 12:35:04      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:play   solution   spl   controls   动态规划   color   display   size   ret   

技术图片

 

 动态规划

class Solution {
public:
    string longestPalindrome(string s) {
        int dp[1100][1100];
        int len=s.size(),ans=1;
        int left=0,right=0;
        for(int i=0;i<len;i++){
            for(int j=i+1;j<len;j++){
                dp[i][j]=0;
            }
            dp[i][i]=1;
            if(s[i]==s[i+1]){
                dp[i][i+1]=1;
                ans=2;
                left=i;right=i+1;
            }
        }
        for(int L=3;L<=len;L++){
            for(int i=0;i+L-1<len;i++){
                int j=i+L-1;
                //cout<<i<<", "<<j<<endl;
                if(s[i]==s[j]&&dp[i+1][j-1]==1){
                    dp[i][j]=1;
                    ans=L;
                    left=i;right=j;
                }
            }
        }
        //cout<<left<<right<<ans<<endl;
        return s.substr(left,right-left+1);
    }
}; 

 

leetcode5 最长回文子串

标签:play   solution   spl   controls   动态规划   color   display   size   ret   

原文地址:https://www.cnblogs.com/joelwang/p/11896820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!