【PAT甲级真题】- Longest Symmetric String (25)

题目来源

Longest Symmetric String (25)

题目描述

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.

输入描述:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

输出描述:

For each test case, simply print the maximum length in a line.

输入例子:

Is PAT&TAP symmetric?

输出例子:

11

思路简介

最长回文有两种写法

  • 中心扩展法:最常用也是最简单好理解的方法,O(n^2)
  • Manacher算法:可以 O(n) 求出所有位置的最长回文串,一般用于多组询问,实际工程上效率可能不如中心扩展

我只简单介绍中心扩展法:

顾名思义,就是从当前位置向两边扩展

用左右指针维护,相同就左指针左移,右指针右移继续比较,不同就退出取最大值

注意

  • 回文有奇回文和偶回文之分,我这里用一个函数就可以区别,可以参考一下代码
  • 指针不能越界

遇到的问题

  1. 没分奇偶回文wa了一次

代码

cpp 复制代码
/**
 * https://www.nowcoder.com/pat/5/problem/4027
 * 最长回文
 */
#include<bits/stdc++.h>
using namespace std;

int expand(string s,int l,int r){
    int len=s.size(),mx=0;
    while(l>=0&&r<len&&s[l]==s[r])l--,r++;
    
    return r-l-1;
}

void solve(){
    string s;
    getline(cin,s);
    int len=s.size(),mx=0;
    for(int i=0;i<len;++i){
        mx=max(expand(s,i,i),mx);//奇回文
        mx=max(expand(s,i,i+1),mx);//偶回文
    }
    cout<<mx;
}

int main(){
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    //fstream in("in.txt",ios::in);cin.rdbuf(in.rdbuf());
    int T=1;
    //cin>>T;
    while(T--){
        solve();
    }
    return 0;
}
相关推荐
To_OC6 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
炸膛坦客7 小时前
单片机/C/C++八股:(二十六)IIC 专题(I²C)---- 上集
c语言·c++·单片机
旖-旎7 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC7 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
Henry Zhu1237 小时前
C++中的特殊成员函数与智能指针
c++
delishcomcn8 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹8 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术9 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
_wyt00110 小时前
多重背包问题详解
c++·背包dp