@[力扣–C语言实现最长回文子串]
题目
给你一个字符串 s,找到 s 中最长的回文子串。
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
代码
char * longestPalindrome(char * s){
char *start = NULL, *end = NULL;
/*这里我原本想赋值成NULL,但是如果最长回文长度为1会出错,最好还是都赋值成s*/
char *mapstart = s
char *p = s;
int maxmap = 1;
/*注意,因为这里是字符串,s最后一位是\0,所以可以这么判断,但不能用于超出字符串范围的判断,因为超出字符串范围后*p也是有值的,就是是随机值,并且可能不是char类型,所以会报错*/
while(*p)
{
start = p;
end = p;
while(*(end + 1) && *end == *(end +1))
{
end++;
}
/*匹配方法:中心扩散:这里为什么start > s 也是出于上面那个注释的考量,不能start = s,否则start - 1 会超出字符串范围*/
while((start > s) && *(end+1) && *(start - 1) == *(end + 1))
{
start--;
end++;
}
/*有超过目前现存最长的回文子串时就更新该回文子串起始位置maxstart以及长度maxmap*/
if((end - start + 1) > maxmap)
{
maxmap = end - start + 1;
mapstart = start;
}
p++;
}
/*分配空间:这里多分配一位存储字符串最后的\0*/
char *ans = (char *)calloc(maxmap + 1,sizeof(char));
/*赋值:拷贝起始地址=mapstart ,len=maxmap的值给ans*/
strncpy(ans , mapstart , maxmap);
return ans;
}