给你一个字符串 s,找到 s 中最长的回文子串。
如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。
示例 1:
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:
输入:s = "cbbd"
输出:"bb"
直接暴力破解吧!
思路:采用暴力查找最长字串。指针p依次从第二个位置开始往后移动,再每个p位置,两个左右指针往两边分别进行基数回文串的匹配和偶数回文串的匹配。若找到回文串,且长度大于上一次记住的max,则用start和end两个指针保存左右两边的位置,最后在end指针后一个位置赋值为’\0’表示字符串结束,原地返回start指针。
代码如下:
char * longestPalindrome(char * s)
{
char *p = s;
char *q;
char *pright,*pleft;
char *start,*end;
int max=0;
p++;
while(*p!='\0')
{
q = p;
if(*(q++) == '\0')
break;
pright = p;
pleft = p;
while(pright!='\0' && pleft >= s) //奇数查找
{
pright++;
pleft--;
if(pleft < s)
break;
if(*pright == *pleft)
{
continue;
}
else
break;
}
pleft++;
pright--;
if(pright!= p && max <pright-pleft+1)
{
start = pleft;
end = pright;
max = pright-pleft+1;
}
pright = p;
pleft = p;
while(pright!='\0' && pleft >= s) //偶数查找
{
pleft--;
if(pleft < s)
break;
if(*pright == *pleft)
{
pright++;
}
else
break;
}
pleft++;
pright--;
if(max < pright-pleft+1)
{
start = pleft;
end = pright;
max = pright-pleft+1;
}
p++;
}
if(max == 0)
{
start = s;
end = s;
}
*(end+1) = '\0';
return start;
}