题目:
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 Specification:
Each input file contains one test case which gives a non-empty string of length no more than 1000.
Output Specification:
For each test case, simply print the maximum length in a line.
Sample Input:Is PAT&TAP symmetric?Sample Output:
11思路:
1.空格也算进去,用getline();
2.注意对称的有奇数情况和偶数情况:
2.1)奇数情况比较两侧字符;
2.2)偶数情况比较自身和后一位字符的大小;
3.要注意最小的长度是1,只要有字母就有长度!!!
代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
getline(cin,s);
int i,n1,n2;
int max = 1; //初始大小为1
for (i = 0; i < s.size() - 1; ++i)
{
if (s[i] == s[i + 1]) //偶数情况
{
for (n1 = i, n2 = i + 1; (n1 >= 0) && (n2 < s.size()); --n1, ++n2)
{
if (s[n1] != s[n2])
break;
}
if (max <(n2 - n1 - 1))
max = n2 - n1 - 1;
}
if ((i > 0) && (s[i - 1] == s[i + 1])) //奇数情况
{
for (n1 = i - 1, n2 = i + 1; (n1 >= 0) && (n2 < s.size()); --n1, ++n2)
{
if (s[n1] != s[n2])
break;
}
if (max <(n2 - n1 - 1))
max = n2 - n1 - 1;
}
}
cout << max << endl;
system("pause");
return 0;
}