1040. Longest Symmetric String (25)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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<cstdio> 2 #include<algorithm> 3 #include<iostream> 4 #include<cstring> 5 #include<queue> 6 #include<vector> 7 #include<cmath> 8 #include<string> 9 #include<map> 10 #include<set> 11 using namespace std; 12 int dp[20005]; 13 int main(){ 14 //freopen("D:\\INPUT.txt","r",stdin); 15 //scanf("%s",s); 16 string s; 17 getline(cin,s); 18 19 //cout<<s<<endl; 20 21 int i,j=0,k,count=0; 22 dp[j++]=-1; 23 for(i=0;i<s.length();i++){ 24 dp[j++]=s[i];//hash 25 dp[j++]=-1; 26 } 27 28 //cout<<j<<endl; 29 30 for(i=1;i<j;i++){//i从1开始!! 31 int f=i-1,b=i+1; 32 while(f>=0&&b<j&&dp[f]==dp[b]){ 33 f--; 34 b++; 35 } 36 if(count<b-f-1){ 37 count=b-f-1; 38 //cout<<count<<endl; 39 } 40 } 41 printf("%d\n",count/2);//这里可以分为中心为-1和正常数字 2种情况讨论 42 return 0; 43 }
方法二:分奇偶别讨论:
1 #include<cstdio> 2 #include<algorithm> 3 #include<iostream> 4 #include<cstring> 5 #include<queue> 6 #include<vector> 7 #include<cmath> 8 #include<string> 9 #include<map> 10 #include<set> 11 using namespace std; 12 int main(){ 13 //freopen("D:\\INPUT.txt","r",stdin); 14 //scanf("%s",s); 15 string s; 16 getline(cin,s); 17 18 //cout<<s<<endl; 19 20 int i,j,k,count=0; 21 for(i=0;i<s.length();i++){ 22 int f=i,b=i; 23 while(f>=0&&b<s.length()&&s[f]==s[b]){ 24 f--; 25 b++; 26 } 27 if(count<b-f-1){ 28 count=b-f-1; 29 } 30 f=i; 31 b=i+1; 32 while(f>=0&&b<s.length()&&s[f]==s[b]){ 33 f--; 34 b++; 35 } 36 if(count<b-f-1){ 37 count=b-f-1; 38 } 39 } 40 printf("%d\n",count); 41 return 0; 42 }
时间: 2024-11-03 05:34:25