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 <cstdio> using namespace std; string s; int len; void getlen(int l, int r){ while(l >= 0 && r < s.size() && s[l--] == s[r ++]) len = max(r - l - 1, len); } int main(){ getline(cin, s); for (int i = 0; i < s.size(); i++) getlen(i, i), getlen(i, i + 1); printf("%d", len); return 0; }