【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;
}
相关推荐
海绵宝宝转agent16 分钟前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
octopus_c22 分钟前
C++ 运算符重载详解 && 日期类的实现
开发语言·c++
青少儿编程课堂25 分钟前
2026蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:堆排序与优先队列解析
c++·python·算法·bfs·信息学竞赛
j7~31 分钟前
【C++ 面试笔记】(篇二):类与数据抽象 & STL 容器与算法
开发语言·c++·面试·stl容器和算法·类和数据抽象
Fuyo_11191 小时前
深入解析 C++ unordered_set 与 unordered_map 的核心特性与性能实战
开发语言·c++
码匠许师傅1 小时前
【C++三方组件】FFmpeg:音视频处理的瑞士军刀
c++·ffmpeg·音视频
SZYSK1 小时前
OpenHarmony 上读卡、推理和双屏刷新抢 CPU:核验机与消费机的调度差
物联网·算法·harmonyos·1024程序员节
ShineWinsu1 小时前
对于Qt:QPushButton常见属性的解析
开发语言·c++·qt·api·gui·按钮·qpushbutton
Ivanqhz1 小时前
MoE + LLM 应用
数据库·人工智能·pytorch·python·深度学习·算法·1024程序员节
Lhan.zzZ1 小时前
用 Qt 构建线程安全的通讯静态库:从线程亲和性到完整工程
c++·vscode·qt·tcp/ip·udp