Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given “Is PAT&TAP symmetric?”, the longest symmetric sub-string is “s PAT&TAP s”, hence you must output 11.
Input
Each input file contains one test case which gives a non-empty string of length no more than 1000.
Output
For each test case, simply print the maximum length in a line.
Sample Input
Is PAT&TAP symmetric?
Sample Output
11
【题目大意】
给出一个字符串,输出最长的对称子串(回文子串)的长度。例如字符串 “Is PAT&TAP symmetric?” 最长对称字串是”s PAT&TAP s”,输出它的长度 11。
【数据范围】
非空字符串,长度 <= 1000
【解题思路】
枚举起点和终点,check() 函数判断每个子串是否对称。
占着数据量小的无脑暴力。
注意一下 maxx 初始化为 1(串非空,单个字符一定是对称的)。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1000+10;
const int INF = 0x3f3f3f3f;
string s;
bool dp[MAXN][MAXN];
bool check(int l, int r) {
while (r > l) {
if (s[l++] != s[r--])
return false;
}
return true;
}
int main () {
// freopen("in.txt", "r", stdin);
getline(cin, s);
int maxx = 1;
for (int i = 0; i < s.length(); i++)
for (int j = i+1; j < s.length(); j++)
if (check(i, j)) maxx = max(j-i+1, maxx);
printf("%d\n", maxx);
return 0;
}
提交时间 | 状态 | 分数 | 题目 | 编译器 | 耗时 |
---|---|---|---|---|---|
2018/7/21 19:37:43 | 答案正确 | 25 | 1040 | C++ (g++) | 105 ms |
2018/7/21 19:32:22 | 部分正确 | 23 | 1040 | C++ (g++) | 45 ms |
2018/7/21 19:31:52 | 部分正确 | 19 | 1040 | C++ (g++) | 46 ms |
19 分是因为记录最小长度的 maxx 初始化为 0 了
23 分的是觉得,如果前一个子串 (i, j-1) 是对称的,那么加上一个字母后的子串 (i, j) 就不用判断了,一定不会对称(简直智障),事实上如果前一个是 AAA,那么加上一位 A 依然是……
这个耗时简直没眼看~
好像有个马拉车算法处理回文的,记录一下