1040 Longest Symmetric String
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
题意:
找出最长的对称子串。
思路:
遍历字符串,以字符串中的每一个字符为对称中心,向两边查找。因为不知道对称子串的长度是奇数还是偶数,所以两种情况都要考虑,取最大值。
Code:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int main() { 6 string str; 7 getline(cin, str); 8 int p1, p2, temp, ans = 1; 9 int len = str.length(); 10 for (int i = 0; i < len; ++i) { 11 p1 = i; 12 p2 = i + 1; 13 temp = 0; 14 while (p1 >= 0 && p2 < len) { 15 if (str[p1--] == str[p2++]) 16 temp += 2; 17 else 18 break; 19 } 20 if (temp > ans) ans = temp; 21 } 22 for (int i = 0; i < len; ++i) { 23 p1 = p2 = i; 24 temp = -1; 25 while (p1 >= 0 && p2 < len) { 26 if (str[p1--] == str[p2++]) 27 temp += 2; 28 else 29 break; 30 } 31 if (temp > ans) ans = temp; 32 } 33 cout << ans << endl; 34 return 0; 35 }
永远渴望,大智若愚(stay hungry, stay foolish)