pat1040. Longest Symmetric String (25)

本文介绍两种高效算法来寻找给定字符串中最长的对称子串及其长度。方法一通过插入无效字符并遍历一次实现;方法二针对奇偶中心分别进行讨论。这两种方法都避免了重复检查,提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 }

 

转载于:https://www.cnblogs.com/Deribs4/p/4770252.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值