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"
题解:
class Solution {
public:
string longestPalindrome(string s) {
int n = s.length();
if (n < 2) {
return s;
}
int maxi = 1, begin = 0;
for (int i = 0; i < n; i++) {
if (s[i] == s[i + 1]) {
int j = i, k = i + 1;
while (s[j] == s[k] && j >= 0 && k < n) {
k++;
j--;
}
maxi = max(maxi, k - j - 1);
if (maxi == k - j - 1) {
begin = j + 1;
}
}
if (i >= 1 && s[i - 1] == s[i + 1]) {
int j = i - 1, k = i + 1;
while (s[j] == s[k] && j >= 0 && k < n) {
k++;
j--;
}
maxi = max(maxi, k - j - 1);
if (maxi == k - j - 1) {
begin = j + 1;
}
}
}
string ans = s.substr(begin, maxi);
return ans;
}
};