Longest Palindromic Substring

Description:

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.

Code:

  string longestPalindrome(string s) {
        if (s=="")
            return s;
        unsigned int n = s.size();
        
        int max_start = 0, max_end = 0;
       bool table[1000][1000];
       for (int i = 0; i < n-1; ++i)
       {
           table[i][i] = true;
           table[i][i+1] = (s[i]==s[i+1])?true:false;
           if (table[i][i+1])
           {
               max_start = i;
               max_end = i+1;
           }
       }
       table[n-1][n-1] = true;
       
      
       for (int len = 3; len <= n; ++len)
       {
           for (int i = 0; i < n-len+1; ++i)
            {
                int j = i+len-1;
                if (s[i]==s[j])
                {
                    table[i][j] = table[i+1][j-1];
                    if (table[i][j])
                    {
                        if (j-i+1 > max_end-max_start+1)
                        {
                            max_start = i;
                            max_end = j;
                        }
                    }
                }
                else
                    table[i][j] = false;
            }
           
       }
        return s.substr(max_start, max_end-max_start+1);
    }

 

posted @ 2015-09-02 15:38  Rosanne  阅读(139)  评论(0编辑  收藏  举报