对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&TAP s",于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11

参考:https://www.liuchuo.net/archives/2102
注意:偶数的情况的是字符串的长度初始是0,奇数的时候是1
#include <iostream>
#include <string>
using namespace std;
int main()
{
int maxvalue = 1;
int temp = 1;
string str;
getline(cin, str);
int len = str.size();
for (int i = 0; i < len; ++i) {
temp = 1;
for (int j = 1; j < len; ++j) {
if (i - j<0 || i + j>len || str[i - j] != str[i + j])
break;
temp = temp + 2;
}
maxvalue = (temp > maxvalue) ? temp : maxvalue;
temp = 0;//注意这里temp也要重置,而且是置成0不是1!!
for (int j = 1; j < len; ++j) {
if (i - j + 1 < 0 || i + j > len || str[i - j + 1] != str[i + j])
break;
temp = temp + 2;
}
maxvalue = (temp > maxvalue) ? temp : maxvalue;
}
cout << maxvalue;
system("pause");
return 0;
}
网友评论