当前位置:网站首页>1040 Longest Symmetric String

1040 Longest Symmetric String

2022-07-05 05:51:00 Brosto_Cloud

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 <algorithm>
#include <string>
using namespace std;

int main() {
	string s;
	int ans, maxx = -1;
	getline(cin, s);
	for (int i = 0; i < s.size(); i++) { //奇数情况
		int j = i - 1, k = i + 1;
		ans = 1;
		while (j >= 0 && k < s.size() && s[j] == s[k]) {
			ans += 2;
			j--;
			k++;
		}
		maxx = max(maxx, ans);
	}
	for (int i = 0; i < s.size(); i++) {
		int j = i, k = i + 1;
		ans = 0;
		while (j >= 0 && k < s.size() && s[j] == s[k]) {
			ans += 2;
			j--;
			k++;
		}
		maxx = max(maxx, ans);
	}
	cout << maxx;
	return 0;
}

 

原网站

版权声明
本文为[Brosto_Cloud]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_53199925/article/details/125596701