PAT 1040

题目 : Longest Symmetric String

分值 : 25
难度 : 中等题
思路 : 遍历最大字符长度到1,依次搜索这个长度下的所有子字符串是否回文
坑点 : reverse substr的运用
评语 : 想到就很简单,代码简短精炼

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s ;
getline(cin ,s ) ;
int length = s.length();
int flag = 0 ;
for(int i = length ; i>= 0 ; i--)
{
for(int start = 0 ; start+i < length ; start++)
{
string temp = s.substr(start,i);
string temp2 = temp;
reverse(temp.begin() , temp.end());
if(temp == temp2)
{
cout << i << endl ;
flag = 1 ;
break ;
}
}
if(flag)
break ;
}
}