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

LeetCode:Longest Palindromic Substring

时间:2014-11-27 14:36:22      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   2014   

题目描述:

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.


解题思路:用动态规划的方法。用isPal[i][j]来表示字符串从i到j是否为回文字串。当S[i]=S[j]时,isPal[i][j]=isPal[i+1][j-1],如果此时字串的长度大于 记录的最大长度,则更新最大长度,且记录下回文字串的位置。当S[i]!=S[j]时,isPal[i][j] = false。动态规划的过程从字串长度为1一直到字串长度为n,结束后就得到了最长回文字串。


代码:

string Solution::longestPalindrome(string s)
{
    if(s.length() == 0 || s.length() == 1)
        return s;

    int length = s.length();
    int max_length = 1;
    int left,right;

    bool  isPal[1000][1000];


    for(int i = 0;i < length;i++)
        for(int j = 0;j < length;j++)
    {
        if(i >= j)
            isPal[i][j] = true;
        else
            isPal[i][j] = false;
    }

    for(int i = 1;i < length;i++)
        for(int j = 0; (i+j) < length;j++)
    {
        int k = i+j;
        if(s[j] != s[k])
            isPal[j][k] = false;
        else
        {
            isPal[j][k] = isPal[j+1][k-1];
            if(isPal[j][k])
            {
                if(i+1 > max_length)
                {
                    max_length = i+1;
                    left = j;
                    right = i+1;
                }
            }
        }
    }

    return s.substr(left,right);
}


LeetCode:Longest Palindromic Substring

标签:style   blog   io   ar   color   sp   for   on   2014   

原文地址:http://blog.csdn.net/yao_wust/article/details/41544553

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