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.
Example:
Input: "cbbd"
Output: "bb"
题意:最长回文字符串,用一个二维矩阵来表示,最初从对角线(左上到右下,代表单个字符)开始,然后依次往上进行对角线(两个字符,多个字符)处理。
class Solution {
public:
string longestPalindrome(string s) {
int len = s.length();
int maxLen = 0;
int longestBegin = 0;
vector<vector<bool> > vec(len, vector<bool>(len, false));
for(int i = 0; i < len; ++i){//单个字符
vec[i][i] = true;
maxLen = 1;
longestBegin = i;
}
for(int i = 0; i < len - 1; ++i){//相邻两个相等的字符
if(s[i] == s[i + 1]){
maxLen = 2;
longestBegin = i;
vec[i][i + 1] = true;
}
}
for(int l = 3; l <= len; ++l){
for(int i = 0; i < len - l + 1; ++i){
int j = i + l - 1;
if(s[i] == s[j] && vec[i + 1][j - 1]){
maxLen = l;
longestBegin = i;
vec[i][j] = true;
}
}
}
return s.substr(longestBegin, maxLen);
}
};