LeetCode-005: Longest Palindromic Substring

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32360995/article/details/86228371

题目:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

题意:

求给定字符串的最长回文子串

思路:

还是熟悉的味道,熟悉的配方,不禁回想起在和朋友在acm的时光~一波Manacher就能解决问题了,水题,有时间在整个模板放上来,还有动态规划的解法~~~懒人一枚

Code:

class Solution {
public:
    string longestPalindrome(string s) {
        int len=s.length();
        if(len==1) return s;
        string str="$#";
        for(int i=0;i<len;i++){
            str+=s[i];
            str+='#';
        }
        len=str.length();
        str[len]='\0';
        int i,maxr=0,mx=0,id,p[2*len],pos;
        for(i=1;str[i]!='\0';i++){
            if(mx>i) p[i]=min(p[2*id-i],mx-i);
            else p[i]=1;
            while(str[i+p[i]]==str[i-p[i]]) p[i]++;
            if(i+p[i]>mx){
                mx=i+p[i];
                id=i;
            }
            if(maxr<p[i]){
                maxr=p[i];
                pos=i;
            }
        }
        return s.substr((pos-p[pos])/2,maxr-1);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32360995/article/details/86228371