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
Ω
输出最长对称子串的长度,简洁明了,跟这篇博客一样,我喜欢。
对于对称字符串我们可以根据对称中心点去寻找,而中心点可能是字符(奇对称)也可能是两个字符中间(偶对称),那么中心点共有种选择。然后计算中心点周围两个邻近字符的索引,循环找出最长对称子串。
C ☺ D E
#include <iostream>
using namespace std;
int main()
{
string s;
getline(cin, s);
int max = 1;
for (int i = 0; i < 2 * s.size(); ++i)
{
int left = i / 2, right = (i + i % 2) / 2 + 1, sum = i % 2;
while (left >= 0 && right < s.size())
{
if (s[left--] == s[right++])
sum += 2;
else
break;
}
if (sum > max)
max = sum;
}
cout << max;
}