题目
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例
输入: “babad”
输出: “bab”
注意: “aba” 也是一个有效答案。
题解
class Solution {
public:
string longestPalindrome(string s) {
int front = 0, end = 0, f, e, ff, ee, flag;
int s_length = s.length();
int ans_length = 0;
for(int i = 0;i < s_length;i++){
flag = 0;
for(f = i,e = i;f >= 0&&e < s_length;f--,e++){
if(s[f] != s[e]){
flag = 1;
break;
}
}
ff = f+1;
ee = e-1;
if(ee - ff + 1 > ans_length){
ans_length = ee - ff + 1;
front = ff;
end = ee;
}
}
for(int i = 0;i < s_length-1;i++){
flag = 0;
for(f = i,e = i+1;f >= 0&&e < s_length;f--,e++){
if(s[f] != s[e]){
flag = 1;
break;
}
}
ff = f+1;
ee = e-1;
if(ee - ff + 1 > ans_length){
ans_length = ee - ff + 1;
front = ff;
end = ee;
}
}
return s.substr(front, ans_length);
}
};