码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Palindromic Substring

时间:2015-09-02 15:57:57      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

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

 技术分享

Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4778761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!