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, and there exists one unique longest palindromic substring.

class Solution {
public:
    string longestPalindrome(string s) 
    {
        int n=s.length();
        int longest[n];
        int max=1;
        int pend=0;
        //1 3 5 
        for(int i=0;i<n;i++) longest[i]=1;
        
        for(int l=3;l<=n;l=l+2)
        {
            for(int i=n-1;i>=-1;i--)
                if(longest[i-1]==l-2 && s[i]==s[i-l+1])
                {
                    longest[i]=l;
                    if(max<l)
                    {
                        max=l;pend=i;
                    }
                }
        }
        //2 4 6
        for(int i=0;i<n;i++) longest[i]=0;
        for(int l=2;l<=n;l=l+2)
        {
            for(int i=n-1;i>=-1;i--)
                if(longest[i-1]==l-2 && s[i]==s[i-l+1])
                {
                    longest[i]=l;
                    if(max<l)
                    {
                        max=l;pend=i;
                    }
                }
        }
        string result="";
        for(int i=pend;i>=pend-max+1;i--)
            result=s[i]+result;
        return result;
    }
}; 
posted @ 2014-05-29 15:06  erictanghu  阅读(116)  评论(0编辑  收藏  举报