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

[LeetCode] Longest Palindromic Substring

时间:2015-01-25 11:03:14      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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.

方法一:动态规划

DP, and the state transfer:

f(i, j) = ture; if i == j
    S[i] == S[j] ,if j = i + 1
    S[i] == S[j] and f(i + 1, j - 1) ,if j > i + 1

class Solution {
    public:
        string longestPalindrome(string s)
        {
            size_t len = s.size();
            char f[len][len];
            size_t start = 0;
            size_t max = 0;

            memset(f,0,sizeof(f));

            for(int i = 0; i < len; i++)
            {
                for(int j = 0; j <= i; j++)
                {
                    if((j == i) || (i == (j+1) && s[i] == s[j])
                            || ((i > (j + 1)) && s[i] == s[j] && f[j+1][i-1]))
                    {
                        f[j][i] = 1;
                        //cout << "f["<<j<<"][" <<i<<"]\n";

                        if((i - j +1) > max)
                        {
                            start = j;
                            max = i - j + 1;
                        //    cout << "start\t" <<start <<endl;
                        //    cout << "max\t" <<max<<endl;
                        }
                    }
                }
            }
            return s.substr(start, max);
        }
};

 

方法二:LCS+ reverse str

 

[LeetCode] Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4247833.html

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