题解:P15012 再生
本蒻蒟的第一篇题解,有意见请提出。
这道题目其实就是一个最长重复子序列,寻找出现过两次以上的字符。
- 通过统计字符串中每个字符的出现次数,找出出现最多的字符。
- 若该字符出现次数小于2,则无法构成至少两次的子序列,输出-1。
- 若出现次数为2,则最长重复子序列长度为2。
- 否则,最长重复子序列长度为该字符的最大出现次数。
实现很简单,可通过代码自行理解。
#include<bits/stdc++.h> using namespace std; int n; string s; int main() { cin>>n>>s; vector<int> last(26,-1); int ans=0; for (int i=0;i<n;i++) { int c=s[i]- 'a'; if (last[c]!=-1){ ans=max(ans,n-(i-last[c])); } last[c]=i; } if (ans==0) { cout<<-1<<endl; } else{ cout<<ans<<endl; } return 0; }