对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
#include <stdio.h>
#include <string.h>
int main()
{
char str[1010];
gets(str);
int len = strlen(str);
int max = 1, temp;
for (int i = 0; i < len; i++) {
temp = 1; //回文序列长度为奇数
for (int j = 1; j < len; j++) {
if (i - j >= 0 && i + j <= len - 1 && str[i - j] == str[i + j])
temp += 2;
else
break;
}
if (temp > max)max = temp;
temp = 0; //回文序列长度为偶数
for (int j = 0; j < len; j++) {
if (i - j >= 0 && i + 1 + j <= len - 1 && str[i - j] == str[i + 1 + j])
temp += 2;
else
break;
}
if (temp > max)max = temp;
}
printf("%d", max);
return 0;
}
注意事项:
考虑两种情况即可:考虑奇数长度时,从当前字符开始,向左向右逐字符判断;考虑偶数长度时,从当前字符和下个字符开始,向左向右逐字符判断。注意数组下标不要越界。
如有问题,欢迎提出。