【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;
}
相关推荐
环黄金线HHJX.4 小时前
龙虾钳足启发的AI集群语言交互新范式
开发语言·人工智能·算法·编辑器·交互
Omics Pro4 小时前
虚拟细胞:开启HIV/AIDS治疗新纪元的关键?
大数据·数据库·人工智能·深度学习·算法·机器学习·计算机视觉
旖-旎4 小时前
分治(快速选择算法)(3)
c++·算法·leetcode·排序算法·快速选择
_日拱一卒5 小时前
LeetCode:合并区间
算法·leetcode·职场和发展
xiaoye-duck5 小时前
【C++:哈希表封装】哈希表封装 myunordered_map/myunordered_set 实战:底层原理 + 完整实现
数据结构·c++·散列表
汀、人工智能5 小时前
[特殊字符] 第3课:最长连续序列
数据结构·算法·数据库架构·图论·bfs·最长连续序列
少许极端5 小时前
算法奇妙屋(四十一)-贪心算法学习之路 8
学习·算法·贪心算法
A.A呐5 小时前
【C++第二十三章】C++11
开发语言·c++
Kethy__5 小时前
计算机中级-数据库系统工程师-数据结构-图
数据结构·算法·软考··数据库系统工程师·计算机中级
亿秒签到6 小时前
L2-007 家庭房产
数据结构·c++·算法