Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
p[i][j]表示字符序列i到j间的回文状态
if p[i+1][j-1]==True && s[i] == s[j]:
p[i][j] = True
C++
class Solution { public: string longestPalindrome(string s) { bool p[1002][1002]; memset(p, false, sizeof(p)); int n = s.length(); for(int i=0; i<n; i++) p[i][i] = true; int maxgap = 0; for(int i=n-1; i>=0; i--) { for(int j=i+1; j<n; j++) { if((i+1 > j-1 || p[i+1][j-1]) && s[i] == s[j]) { p[i][j] = true; maxgap = max(maxgap, j-i+1); } } } int i, j=n-1; cout<< maxgap<<endl; for(i=0; i<n; i++, j=n-1) { while(j>i && p[i][j]==false) j--; if(j>i && j-i+1 == maxgap) break; // found the final result } // cout<< i<<" " <<j<<endl; if(i >= j) return s.substr(0, 1); else return s.substr(i, j-i+1); } };