思路
一个中心是指回文子串的对称中心,两个基本点是指回文子串的起点和终点
首先是找中心,我分了两种情况:
一是连续相等的情况,就直接找到连续相等子串的中心,作为对称中心;
二是不相等的情况,就找到一对离得最近的相同字符,作为对称中心。
然后是找两个基本点,就直接从中心开花,向两边遍历,就能找到回文子串起点和终点。
每找到一个子串记录一次子串长度,如果大于最大值,就更新起点和终点,否则不变。
代码
//思路:右移寻找中心,然后扩散
char* longestPalindrome(char* s) {
int i;
struct huiwen temp, max;
max.start = max.end = 0;
int len = strlen(s);
for (i = 0; i < len;) {
temp.start = temp.end = i;//指向中心
while (s[temp.start] == s[temp.end + 1])
temp.end++;//中心为奇数或者偶数
while (temp.start-1 >= 0 && temp.end+1 <= len) {//大前提
if (s[temp.end + 1] == s[temp.start - 1]) {//不断扩散
temp.end++;
temp.start--;
}
else
break;
}
if (temp.end - temp.start > max.end - max.start)
max = temp;
i = temp.end + 1;//中心右移
}
s[max.end + 1] = '\0';
return s + max.start;
}