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思路:最长回文子串,O(n^2)的算法。本次算法编程知道了一些语法上的问题例如:用string时 如用cin>>输入那么就会产生遇到空格断开,并且gets()不能读取string。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 using namespace std; 6 #define MAX 1010 7 int dp[MAX][MAX]; 8 int ans; 9 int main(int argc, char *argv[]) 10 { 11 char str[MAX]; 12 //cin>>string 也是读到空格结束 get不能读string 13 gets(str); //在cstdio中 14 int len=strlen(str); 15 memset(dp,0,sizeof(dp)); 16 ans=1; 17 //对dp进行初始化 18 for(int i=0;i<len;i++) 19 { 20 dp[i][i]=1; 21 if(i<len-1) 22 { 23 if(str[i]==str[i+1]) 24 { 25 dp[i][i+1]=1; 26 ans=2; 27 } 28 } 29 30 } 31 for(int l=3;l<=len;l++) 32 { 33 for(int i=0;i+l-1<len;i++) 34 { 35 int j=i+l-1; 36 if(str[i]==str[j]) 37 { 38 dp[i][j]=dp[i+1][j-1]; 39 ans=l;// 答案错误 如何dp[i+1][j-1]=0的时候那么不成立 40 } 41 else 42 dp[i][j]=0; 43 } 44 } 45 cout<<ans<<endl; 46 return 0; 47 }
时间: 2024-10-13 12:06:19