题目来源
题目描述
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)求出所有位置的最长回文串,一般用于多组询问,实际工程上效率可能不如中心扩展
我只简单介绍中心扩展法:
顾名思义,就是从当前位置向两边扩展
用左右指针维护,相同就左指针左移,右指针右移继续比较,不同就退出取最大值
注意
- 回文有奇回文和偶回文之分,我这里用一个函数就可以区别,可以参考一下代码
- 指针不能越界
遇到的问题
- 没分奇偶回文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;
}