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();
char *ans;
ans = (char *)malloc(len + 1);
fill(&ans[0], &ans[len], '\0');
int i;
int maxlen = -1;
for (i = 0; i < len; i++) {
int l = i, r = i;
while (l >= 0 && r <= len - 1 && s[l] == s[r]) {
l--;
r++;
}
l++;
r--;
if (r - l + 1 > maxlen) {
maxlen = r - l + 1;
memcpy(ans, &s[l], maxlen);
}
}
for (i = 0; i < len; i++) {
int l = i, r = i+1;
while (l >= 0 && r <= len - 1 && s[l] == s[r]) {
l--;
r++;
}
l++;
r--;
if (r - l + 1 > maxlen) {
maxlen = r - l + 1;
memcpy(ans, &s[l], maxlen);
}
}
string out = ans;
return out;
}
};