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

Leetcode:Longest Palindromic Substring 最长回文子串

时间:2014-06-21 07:36:18      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   tar   

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.

 

解题分析:

f[i][j]表示[i,j]之间的最长回文子串,递推方程如下:

bubuko.com,布布扣

class Solution {
public:
    string longestPalindrome(string s) {
        if (s.size() == 0) return "";
        const int strLen = s.size();
        bool flag[strLen][strLen];
        memset(flag, false, sizeof(flag));
        //vector<vector<bool>> flag(strLen, vector<bool>(strLen, false));
        int maxLen = 1;
        int start = 0;
        
        for (int i = strLen - 1; i >= 0; --i) {
            flag[i][i] = true;
            for (int j = i + 1; j < strLen; ++j) {
                if (j == i + 1 && s.at(i) == s.at(j)) flag[i][j] = true;
                if (j >  i + 1 && s.at(i) == s.at(j) && flag[i+1][j-1] == true) flag[i][j] = true;
                if (flag[i][j] == true && maxLen < j - i + 1) {
                    maxLen = j - i + 1;
                    start = i;
                }
            }
        }
        return s.substr(start, maxLen);
    }
};

注意:

因为f[i,j] 需要使用到 f[i+1, j-1],所以必须首先计算 f[i+1, j-1], 然后计算 f[i,j] 这样游标i必须从大到小,游标j必须从小到大

Leetcode:Longest Palindromic Substring 最长回文子串,布布扣,bubuko.com

Leetcode:Longest Palindromic Substring 最长回文子串

标签:style   class   blog   code   http   tar   

原文地址:http://www.cnblogs.com/wwwjieo0/p/3795375.html

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