题目描述
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
求解思路
给定一个字符串,要求我们给出最长的子回文串的长度。
- 由于读取的字符串中包括空格符,所以可以使用getline读取。
- 使用暴力枚举的方法,截取字符串判断是否是回文字符串并且其长度是否大于当前的最大长度,如果是则更新反之继续遍历。
代码实现(AC)
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
string s;
bool symmetric(string s)
{
int i=0,j=s.length()-1;
while(i<=j)
{
if(s[i]!=s[j]) return 0;
i++;
j--;
}
return 1;
}
void solve()
{
getline(cin,s);
int maxlen=1;
for(int i=s.length()-1;i>=0;i--)
{
for(int j=0;j<=i;j++)
{
string temp=s.substr(j,i-j+1);
if(symmetric(temp)&&maxlen<temp.length())
{
maxlen=temp.length();
}
}
}
cout<<maxlen;
}
int main()
{
solve();
return 0;
}