[Problems] Given a string s, s to find the longest substring palindromic. You can assume that the maximum length of 1000 s.
Example 1 : Input: " Babad " Output: " BAB " Note: " aba " is a valid answer. Example 2 : Input: " cbbd " Output: " BB "
[Thinking] Two days ago we explained the "Center Expansion Act" to solve This question, today we use dynamic programming approach to written question head, we need to look for a recursive formula is as follows:
We will F [i] [j] is expressed as a string of sub-palindromic sequence from j to i, , j <= i, this case is the lower left triangular matrix dp!
If a [i] == a [j ] and f [i-1] [j + 1] = true, then f [i] [j] is also true.
Note that: when ij <2, if s [i] = s [j], then f [i] [j] will be for true, i.e., a single character or two identical adjacent character substring palindromic.
class Solution { public: string longestPalindrome(string s) { int slen = s.length(); if(slen == 0) return ""; string res = ""; vector<vector<bool>> f(slen, vector<bool>(slen, false)); int maxlen = 0; int curlen = 0; for(int i = 0;i < slen; i++){ for(int j = 0;j <= i; j++){ // f[0][0]=true, 一定成立 if((s[i] == s[j]) && ((i-j < 2) || (i > 0 && f[i-1][j+1]))){ f[i][j] = true; curlen = i - j + 1; if(curlen > maxlen){ maxlen = curlen; res = s.substr(j, curlen); } } } } return res; } };