PAT (Advanced Level) Practice 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;
bool func(string s)
{
    
    
	for(int i = 0;i < s.length();i++)
	{
    
    
		if(s[i] != s[s.length()-i-1])
			return false;
	}
	return true;
}
int main()
{
    
    
	string str;
	getline(cin,str);
	//j放在i前面的原因是j代表长度,控制好长度后,可以在找到字符串的时候直接输出并结束 
	for(int j = str.length();j >= 1;j--)
	{
    
    
		for(int i = 0;i + j <= str.length();i++)
		{
    
    
			if(func(str.substr(i,j)))
			{
    
    
				cout << j;
				return 0;
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43820008/article/details/114213045