L2-008. 最长对称子串

题目:

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&TAP s",于是你应该输出11。

输入格式:

输入在一行中给出长度不超过1000的非空字符串。

输出格式:

在一行中输出最长对称子串的长度。

输入样例:
Is PAT&TAP symmetric?
输出样例:
11

最长对称字串分偶数和奇数进行讨论

代码

#include <cstdio>
#include <iostream>
#include <math.h>
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;

int main()
{
   string a;
   getline(cin,a);
   int i , j;
   int x = a.length();
   int temp,max = 0;
   //遍历字符串
   for(i = 0 ; i < x ;i++)
   {
       //当最长对称字串为奇数时
       temp = 1;
       //以每个i位置的字符为中心,向两边扩展,j为跨度从1开始(对称跨度)
       for(j = 1 ; j < x/2 +1;j++)
       {
           //以i为中心
           if(i-j<0||a[i-j]!=a[i+j])
            break;
           temp+=2;
       }
       if(temp>max)max = temp;
       //偶数
       temp = 0;
       for(j = 1 ; j < x /2 +1 ;j++)
       {
            //以i为中心
           if(i-j+1<0||a[i-j+1]!=a[i+j])
            break;
           temp+=2;
       }
       if(temp>max)max = temp;
   }
   cout<<max<<endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值