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"
以下代码将返回结果变为输出结果方便测试:
#include<iostream>
#include<string>
using namespace std;
class Solution
{
public:
void longestPalindrome(string s) {
int i, j, max = 0, left, right, len, k;
int length = s.length();
len = length;
for (i = 0; i < len; i++) { //以i为中心进行回文检测
for (j = 0;i - j >= 0 && i + j < len; j++) { //奇数字串检测
if (s[i - j] != s[i + j])
break;
if (j * 2 + 1 > max) {
max = j * 2 + 1;
left = i - j;
right = i + j;
}
}
for (j = 0; i - j >= 0 && i + j + 1 < len; j++) { //偶数字串检测
if (s[i - j] != s[i + j + 1])
break;
if ((j + 1) * 2 > max) {
max = (j + 1) * 2;
left = i - j;
right = i + j + 1;
}
}
}
string result;
for (k = left; k <= right; k++)
result += s[k];
cout << result << endl;
}
};
int main() {
Solution *p = new Solution;
string s = "babad";
p->longestPalindrome(s);
system("pause");
return 0;
}
.