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 #include <algorithm> 4 5 using namespace std; 6 string str, t1, t2; 7 int res = 1; 8 //最普通的遍历 9 void way1() 10 { 11 for (int i = 0; i < str.length(); ++i) 12 { 13 for (int j = str.length() - 1; j > i; --J) 14 { 15 t1.assign (str.begin () + I, str.begin () + + J . 1 ); 16 t2.assign (t1.rbegin (), t1.rend ()); . 17 IF (T1 == T2) 18 is RES = RES> t1.length ()? RES: t1.length (); . 19 } 20 is } 21 is } 22 is 23 is // use both sides of the center of the same palindromic substring 24 void Way2 () 25 { 26 is for ( int I = 0 ; I <str.size (); ++ I) { 27 intJ; 28 for (J = . 1 ; I - J> = 0 && I + J <str.size () && STR [I + J] == STR [I - J]; J ++); // the current Find the center of the longest character palindromic palindromic substring 29 RES = max (RES, 2 * J - . 1 ); // update the maximum length of a palindromic substring 30 for (J = 0 ; I - J> = 0 && I + J + . 1 <str.size () && STR [I - J] == STR [I + . 1 + J]; J ++); // to find the current character is the character to the left center of the longest palindromic palindromic substring 31 max = RES (RES, 2 * J); // update the maximum length of a palindromic substring 32 } 33 } 34 35 //使用动态规划 36 void way3() 37 { 38 int dp[1010][1010]; 39 for (int i = 0; i < str.length(); i++) 40 { 41 dp[i][i] = 1; 42 if (i < str.length() - 1 && str[i] == str[i + 1]) 43 { 44 dp[i][i + 1] = 1; 45 res = 2; 46 } 47 } 48 for (int L = 3; L <= str.length(); L++) { 49 for (int i = 0; i + L - 1 < str.length(); i++) { 50 int j = i + L - 1; 51 if (str[i] == str[j] && dp[i + 1][j - 1] == 1) { 52 dp[i][j] = 1; 53 res = L; 54 } 55 } 56 } 57 } 58 59 int main() 60 { 61 getline(cin, str); 62 way1(); 63 cout << res << endl; 64 return 0; 65 }