PAT 1040. Longest Symmetric String (25)(最大对称长度)

来源:互联网 发布:科荣纺织软件 编辑:程序博客网 时间:2024/06/01 10:10

官网

1040. Longest Symmetric String (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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

题目大意

  • 1.求最大的对称的长度,空格也算。

解题思路

  • 1.暴力对每个s[i]求解俩边能对称的个数,然后去最大值。
  • 2.注意分为奇偶俩种情况,例如12321 和 123321。
  • 3.char s[1001];cin.getline(s,1001);用这种方式输入一行字符串。

代码

#include<iostream>#include<string>#include<vector>#include<cstring>//strlenusing namespace std; int main(int argc, char *argv[]){     char s[1001];     cin.getline(s,1001);     int maxlen=strlen(s);     int longest = 0;     for (int i = 0; i < maxlen; ++i) {         //奇数         int k1=0,k2=0;         while (i-k1>=0&&i+k1<maxlen&&s[i-k1]==s[i+k1]) {             k1++;         }         //偶数         while (i-k2>=0&&i+1+k2<maxlen&&s[i-k2]==s[i+1+k2]) {             k2++;         }         k1 = 2 *( k1 - 1 ) +1;         k2 = 2 * k2;         k2 = max(k1,k2);         longest = max(longest,k2);     }     cout<<longest<<endl;    return 0;}
0 0