您的位置:首页 > 其它

PAT 1040. Longest Symmetric String (25)

2015-08-11 14:08 471 查看

1040. Longest Symmetric String (25)

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

对于序列的对称点所在位置进行循环


#include <iostream>
#include <string>

using namespace std;

int main()
{
string s;
getline(cin, s);
int maxlength = 0;
for (int i = 0; i < 2 * s.size() - 1; i++)
{
if (2 * s.size() - i - 1 <= maxlength)
break;

int max=0;
if (i % 2 == 0)
{
int center = i / 2;
++max;
int j = 1;
while (center - j >= 0 && center + j < s.size())
{
if (s[center - j] == s[center + j])
max += 2;
else
break;
j++;
}
}
else
{
int left = (i - 1) / 2;
int right = (i + 1) / 2;
while (left >= 0 && right < s.size())
{
if (s[left] == s[right])
max += 2;
else
break;
left--;
right++;
}
}
if (max > maxlength)
maxlength = max;
}
cout << maxlength;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: