参考的别人的做法,分两种情况
一种是对称的子串长度是偶数,那么从中间2个字符向两边扩展统计
一种是对称的子串长度是奇数,那么从中间1个单独字符向两边扩展统计,包括单独输入一个字符也算对称,长度为1
L2-008. 最长对称子串
时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&TAP s",于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:Is PAT&TAP symmetric?输出样例:
11
#include <iostream> #include <cstring> using namespace std; char c[1001]; int main() { gets(c); int len = strlen(c); int max = 1; for (int i = 0; i < len; ++i) // 对称是偶数情况,哪怕没有max也是为1的 { int ans = 0; int x = i, y = i + 1; while (c[x] == c[y] && x >= 0 && y < len) { --x; ++y; ans += 2; } if (ans > max) { max = ans; // 记录对称为偶数情况子串最大长度 } } for (int i = 1; i < len; ++i) // 对称是奇数情况 { int ans = 1; // 统计的起点包括最中间那个 int x = i - 1, y = i + 1; while (c[x] == c[y] && x >= 0 && y < len) { --x; ++y; ans += 2; } if (ans > max) // 奇数和偶数子串最大的比较,记录最大长度 { max = ans; } } printf("%d ", max); return 0; }
题目链接地址https://www.patest.cn/contests/gplt/L2-008
========================================Talk is cheap, show me the code=======================================