1. 程式人生 > >LeetCode-005: Longest Palindromic Substring

LeetCode-005: Longest Palindromic Substring

題目:

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);
    }
};