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

解题思路

  题目大意: 给一个长度不超过1000的字符串,查找其中最长的回文子串。
  解题思路: 长度不长,时间限制也不严格,直接暴力AC即可,使用STL的std::string::substr函数和algorithm::reverse函数能够大大节省时间,避免重复造轮子。

/*
** @Brief:No.1040 of PAT advanced level.
** @Author:Jason.Lee
** @Date:2018-12-16
** @status: Accepted!
*/
#include
#include
#include

using namespace std;

int main(){
	string input;
	while(getline(cin,input)){
		int max = 0;
		for(int i=0;i<input.length();i++){
			for(int j=i+1;j<=input.length();j++){
				string substr = input.substr(i,j);
				reverse(substr.begin(),substr.end());
				if(substr==input.substr(i,j)&&max<substr.length()){
					max = substr.length();
				}
			}
		} 
		cout<<max<<endl;
	}
	return 0;
} 

1040 Longest Symmetric String (25 分)最长回文子串_第1张图片

总结

  使用reverse做回文是常用手法。

你可能感兴趣的:(PAT-Advanced,Level)