题目:
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例1
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例2
输入: "cbbd"
输出: "bb"
算法实现:中心扩散法
class Solution {
public:
string longestPalindrome(string s) {
int length(1), i(1), j(0);
int size = s.size();
unordered_set<char> set;
if (size == 1 || size == 0)
return s;
string output = "a";
output[0] = s[0];
for (; i < size; i++) {
if (s[i] == s[i - 1]) {
length++;
j = i + 1;
while (j - length - 1 >= 0 && s[j] == s[j - length - 1]) {
length += 2;
j++;
}
if (output.size() < length) output = s.substr(j - length, length);
length = 1;
}
if (i - length - 1 >= 0 && i >= 2 && s[i] == s[i - length - 1]) {
length += 2;
j = i + 1;
while (j - length - 1 >= 0 && s[j] == s[j - length - 1]) {
length += 2;
j++;
}
if (output.size() < length) output = s.substr(j - length, length);
length = 1;
}
}
return output;
}
};