PAT 1040. Longest Symmetric String (25)

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

对于序列的对称点所在位置进行循环
 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     string s;
 9     getline(cin, s);
10     int maxlength = 0;
11     for (int i = 0; i < 2 * s.size() - 1; i++)
12     {
13         if (2 * s.size() - i - 1 <= maxlength)
14             break;
15 
16         int max=0;
17         if (i % 2 == 0)
18         {    
19             int center = i / 2;
20             ++max;
21             int j = 1;
22             while (center - j >= 0 && center + j < s.size())
23             {
24                 if (s[center - j] == s[center + j])
25                     max += 2;
26                 else
27                     break;
28                 j++;
29             }            
30         }
31         else
32         {
33             int left = (i - 1) / 2;
34             int right = (i + 1) / 2;
35             while (left >= 0 && right < s.size())
36             {
37                 if (s[left] == s[right])
38                     max += 2;
39                 else
40                     break;
41                 left--;
42                 right++;
43             }
44         }
45         if (max > maxlength)
46             maxlength = max;
47     }
48     cout << maxlength;
49 }

 

posted @ 2015-08-11 14:08  JackWang822  阅读(137)  评论(0编辑  收藏  举报