PAT 1040. Longest Symmetric String (25)(最大对称长度)

本文介绍了一种求解最长对称子串的算法实现,通过遍历字符串并检查每一点左右两侧的对称性来找出最长的对称子串。文章提供了完整的C++代码示例,展示了如何处理奇数和偶数长度的对称情况。

摘要生成于 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.求最大的对称的长度,空格也算。

解题思路

  • 1.暴力对每个s[i]求解俩边能对称的个数,然后去最大值。
  • 2.注意分为奇偶俩种情况,例如12321 和 123321。
  • 3.char s[1001];cin.getline(s,1001);用这种方式输入一行字符串。

代码

#include<iostream>
#include<string>
#include<vector>
#include<cstring>//strlen
using namespace std;
 int main(int argc, char *argv[])
{
     char s[1001];
     cin.getline(s,1001);
     int maxlen=strlen(s);
     int longest = 0;
     for (int i = 0; i < maxlen; ++i) {
         //奇数
         int k1=0,k2=0;
         while (i-k1>=0&&i+k1<maxlen&&s[i-k1]==s[i+k1]) {
             k1++;
         }
         //偶数
         while (i-k2>=0&&i+1+k2<maxlen&&s[i-k2]==s[i+1+k2]) {
             k2++;
         }
         k1 = 2 *( k1 - 1 ) +1;
         k2 = 2 * k2;
         k2 = max(k1,k2);
         longest = max(longest,k2);
     }
     cout<<longest<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值