题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int repword_count(char str[], int mid, int len) {
int start1 = mid - 1, end1 = mid + 1; //奇数情况,从中间向两边判断
int count1 = 1;
while (start1 >= 0 && end1 < len) {
if (str[start1] == str[end1]) {
count1 += 2;
start1--;
end1++;
} else {
break;
}
}
int start2 = mid, end2 = mid + 1; //偶数情况
int count2 = 0;
while (start2 >= 0 && end2 < len) {
if (str[start2] == str[end2]) {
count2 += 2;
start2--;
end2++;
} else {
break;
}
}
return count1 > count2 ? count1 : count2; //取两种情况的最大值
}
int main() {
char* str = (char*)malloc(sizeof(char) * 350);
int max = 1;
while (~scanf("%s", str)) {
int len = strlen(str);
int tem = 0;
int i = 0;
for (i = 0; i < len - 1; i++) {
tem = repword_count(str, i, len);
max = max < tem ? tem : max;
}
}
printf("%d", max);
}
