题意:
取一字符串不相交的前缀和后缀(可为空)构成最长回文串。
思路:
先从两边取对称的前后缀,之后再取余下字符串较长的回文前缀或后缀。
讲解:
这道题主要是需要考虑的情况太多,比如说只有一个字符的情况下我是用if来判断输出还是用以下这种解法
这个解法的巧妙之处就是在于不用考虑是几个字符,因为在输出1个字符的时候l,r和仍然在以前的位置不会改变,第一个输出时候就是cout<<s.substr(0,0)就什么都不会输出,末尾的话就是比r还大1更不会输出了,但是最好注意string定义的位置,使string每次用的时候都是新的,因为自己还不清楚string定义完后需要在什么情况下清空所以最好每次都情况。
当只有一个字母的时候会输出最后一个字符
#include<bits/stdc++.h> #define INF 0x3f3f3f3f #define DOF 0x7f7f7f7f #define mem(a,b) memset(a,b,sizeof(a)) #define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); typedef long long ll; using namespace std; bool ok(const string s,int l,int r) { while(l<=r&&s[l]==s[r]) ++l,--r; return l>r; } int main() { int t;cin>>t; while(t--) { string s; cin>>s; int len=s.size()-1; int l=0,r=len; while(l<r&&s[l]==s[r]) ++l,--r; int l2,r2; for(r2=r;r2>=l;--r2) { if(ok(s,l,r2)) break; } for(l2=l;l2<=r;++l2) if(ok(s,l2,r)) break; cout<<s.substr(0,l) <<((r2-l>r-l2)?s.substr(l,r2-l+1):s.substr(l2,r-l2+1)) <<s.substr(r+1)<<endl; } }