首页 > 其他 > 详细

leetcode144 longest-palindromic-substring

时间:2020-07-21 11:56:40      阅读:57      评论:0      收藏:0      [点我收藏+]

题目描述

找出给出的字符串S中最长的回文子串。假设S的最大长度为1000,并且只存在唯一解。

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
示例1

输入

复制
"abcba"

输出

复制
"abcba"

动态规划

class Solution {
public:
    /**
     *
     * @param s string字符串
     * @return string字符串
     */
    string longestPalindrome(string str) {
        // write code here
        int n=str.length();
        if (n==0) return "";
        bool dp[n][n];
        fill_n(&dp[0][0],n*n,false);
        int left=0,right=0,maxLen=0;
        for (int j=0;j<n;j++)
        {
            dp[j][j]=true;
            for (int i=0;i<j;i++)
            {
                dp[i][j]=(str[i]==str[j] && (j-i<2 || dp[i+1][j-1]));
                if (dp[i][j]&& (j-i+1>maxLen))
                    {
                        left=i;
                        right=j;
                        maxLen=j-i+1;
                    }
            }
            
        }
                    return str.substr(left,right-left+1);
    }
};

leetcode144 longest-palindromic-substring

原文:https://www.cnblogs.com/hrnn/p/13352990.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!