当前位置: 代码迷 >> 综合 >> PAT 1040 Longest Symmetric String (25)
  详细解决方案

PAT 1040 Longest Symmetric String (25)

热度:108   发布时间:2023-11-20 00:45:12.0
1040 Longest Symmetric String (25)(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


解答:该题求最长对称子串,主要考察string的子字符串匹配,在C++中可以用#include<algorithm>中的reverse(begin, end)求得一个串的逆序串。只要逆序串和原串相同即可。主要的坑点在于:1)最短的最长对称子串为1;2)因为输入的string中允许有空格,因此不能直接用cin >> str, 二是 用 getline(cin ,str)得到包括空格的字符串。

该题的AC代码为:

#include<iostream>
#include<string>
#include<algorithm>
#include<stdio.h>
using namespace std;int main()
{int max_len= 1;   //记录最大的对称子串长度 string s;  //记录读入的string getline(cin , s);for(int i = 0; i < s.length()-1; ++i){for(int j = i + 1; j < s.length(); ++j){int len = j - i + 1;if(s[i] == s[j]){string sub = s.substr(i, len), rsub(sub);reverse(sub.begin(), sub.end());  if(sub == rsub){max_len = max_len > len ? max_len : len;}}}}cout << max_len << endl;return 0;	
} 

  相关解决方案