5. 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.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

寻找最长回文字符串。

用动态规划。dp[i][j]记录从s[i]到s[j]是否为回文。

class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.length();
        vector< vector<int> > dp(len, vector<int>(len));
        string res;
        for( int i=0; i<len; ++i ){
            for( int j=i; j>=0; --j ){
                dp[i][j] = ((s[i]==s[j]) && (i-j<2 || dp[i-1][j+1]));
                if( dp[i][j] && (i-j+1)>res.length() )
                    res = s.substr(j, i-j+1);;
            }
        }
        return res;
    }
};

 

posted @ 2017-11-29 15:01  Zzz...y  阅读(132)  评论(0)    收藏  举报