给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
string longestPalindrome(string s) {
string s_ret;
int pos_begin = 0;
int pos_end = 0;
int str_len = 0;
int str_len_b = 0;
int index = 0;
bool echo_flag = 0;
int sub_id = 0;
bool cons_string = 0;
bool once_entry = 1;
int pos_com = 0;
if(s.size() < 2)
{
return s;
}
for(index = 0; index < (s.size() - 1); index++)
{
pos_begin = index;
pos_end = s.find(s[index], pos_begin+1);
while(pos_end > 0)
{
echo_flag = 1;
if(((pos_end - pos_begin) == 1) && once_entry)
{
cons_string = 1;
}
else
{
cons_string = 0;
once_entry = 0;
}
if(!cons_string)
{
pos_com = index + (pos_end - index)/2;
for(sub_id = index; sub_id <= pos_com; sub_id ++)
{
if(s[sub_id] != s[pos_end - sub_id + index])
{
echo_flag = 0;
break;
}
}
}
if(echo_flag)
{
str_len_b = pos_end - index + 1;
if(str_len_b > str_len)
{
str_len = str_len_b;
s_ret = s.substr(index, str_len);
}
}
pos_begin = pos_end;
pos_end = s.find(s[pos_begin], pos_end + 1);
}
}
if(str_len == 0)
{
str_len = 1;
s_ret = s.substr(0, 1);
}
return s_ret;
}
};