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; }