L2-008. 最长对称子串

本文介绍了一种寻找字符串中最长回文子串的算法实现。通过两次遍历字符串,分别针对奇数长度和偶数长度的回文串进行检测,并记录最长回文串的长度。该算法使用C++编写,利用了gets()获取输入字符串,通过比较相邻字符来扩展可能的回文串。

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

#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>

using namespace std;

int main(void){
  char str[1005];
  gets(str);
  int len = strlen(str);
  int ans = 1;
  for(int i = 0; i < len; i++){
    int L = i - 1,R = i + 1;
    int h = 1;
    while(L >= 0 && R <= len - 1){
      if(str[L] == str[R]){
        L--;
        R++;
        h += 2;
      }
      else{
        break;
      }
      ans = max(ans,h);
    }
  }
  int h;
  for(int i = 1; i < len; i++){
    if(str[i] == str[i - 1]){
      int h = 2;
      int L = i - 2,R = i + 1;
        while(L >= 0 && R <= len - 1){
          if(str[L] == str[R]){
           L--;
             R++;
            h += 2;
          }
          else{
            break;
          }
          ans = max(ans,h);
        }
    }
  }
  cout<<ans<<endl;
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值