您的位置:首页 > 其它

L2-008. 最长对称子串

2018-02-27 17:54 197 查看

题目:

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&TAP s",于是你应该输出11。输入格式:输入在一行中给出长度不超过1000的非空字符串。输出格式:在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
最长对称字串分偶数和奇数进行讨论
代码:#include <cstdio>
#include <iostream>
#include <math.h>
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;

int main()
{
string a;
getline(cin,a);
int i , j;
int x = a.length();
int temp,max = 0;
//遍历字符串
for(i = 0 ; i < x ;i++)
{
//当最长对称字串为奇数时
temp = 1;
//以每个i位置的字符为中心,向两边扩展,j为跨度从1开始(对称跨度)
for(j = 1 ; j < x/2 +1;j++)
{
//以i为中心
if(i-j<0||a[i-j]!=a[i+j])
break;
temp+=2;
}
if(temp>max)max = temp;
//偶数
temp = 0;
for(j = 1 ; j < x /2 +1 ;j++)
{
//以i为中心
if(i-j+1<0||a[i-j+1]!=a[i+j])
break;
temp+=2;
}
if(temp>max)max = temp;
}
cout<<max<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pat