对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
结尾无空行
输出样例:
11
结尾无空行
代码:
第一次写的代码:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string str;
getline(cin,str);
int len=str.size();
int maxn=0;
int temp;
for(int i=0;i<len;i++) //i从0开始
{
//对称字串是奇数时
temp=1;
for(int j=1;j<=len;j++)
{
if(i-j<0||i+j>=len||str[i-j]!=str[i+j])
break; //不满足条件就break
temp+=2;
}
maxn=max(maxn,temp); //当用max函数的时,不能用max当变量
//对称子串是偶数时
temp=0;
for(int j=1;j<len;j++)
{
if(i+1-j<0||i+j>=len||str[i+1-j]!=str[i+j])
break;
temp+=2;
}
maxn=max(maxn,temp);
}
cout << maxn << endl;
}
第二次写的代码:
#include <iostream>
using namespace std;
//该题主要思路就是
//字符串遍历寻找 字符对称的 分为两种 奇数串和偶数串
int main()
{
string s;
getline(cin,s); //cin >> s ;该操作读到' '空格,即停止,所以应该getline (cin, s) 读入字符串
int max_len = 0;
string str1="", str2="";
for (int i = 0; i< s.size(); i ++)
{
int j = 0;
while ((i + j < s.size()) && (i - j >= 0) && (s[i + j] == s[i - j]))
{
j ++;
}
max_len = max (max_len, 2 * j - 1);
int k = 0;
while ((i + k < s.size()) && (i - k - 1 >= 0) && (s[i + k] == s[i - 1 - k]))
{
k ++;
}
max_len = max(max_len, 2 * k);
}
cout << max_len;
return 0;
}