L2-008. 最长对称子串

来源:互联网 发布:网络设计师待遇 编辑:程序博客网 时间:2024/06/06 04:49

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<cstdio>#include<cstring>#include<string>using namespace std;int main(){//freopen("input.txt","r",stdin);string str;getline(cin,str);int max = 1;for(int i = 0;i < str.size();i++){int cnt = 0;if(str[i] != str[i-1]){//关于str[i]对称 ,有对称点 for(int j = 1;j <= i&&j+i<str.size();j++){if(str[i-j]==str[i+j]){cnt++;}else{break;}}if(cnt*2+1>max){max = cnt*2+1;}}else{for(int j = 1;j <= i;j++){//没有对称点的情况 if(str[i+j-1]==str[i-j]){cnt++;}else{break;}}if(cnt*2>max){max = cnt*2;}}}printf("%d\n",max);return 0;} 



原创粉丝点击