Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include<vector>
- #define fastio ios_base::sync_with_stdio(0);cin.tie(NULL);
- using namespace std;
- vector<int> prefix_function(string s) {
- int n = (int)s.length();
- vector<int> pi(n);
- for (int i = 1; i < n; i++) {
- int j = pi[i-1];
- while (j > 0 && s[i] != s[j])
- j = pi[j-1];
- if (s[i] == s[j])
- j++;
- pi[i] = j;
- }
- return pi;
- }
- int KMPSearch(string pat, string txt, int i){
- int lenp=(int)pat.length();
- int lent=(int)txt.length();
- vector<int>lps=prefix_function(pat);
- int j=0;
- int total=0;
- while(i<lent){
- if(pat[j]==txt[i]){
- j++;
- i++;
- }
- if(j==lenp){
- total++;
- j=lps[j-1];
- }
- else if(i<lent && pat[j]!=txt[i]){
- if(j!=0){
- j=lps[j-1];
- }
- else i++;
- }
- }
- return total;
- }
- int main(){
- int L,len,total,highest;
- string x,tmp,temp;
- while(cin>>L,cin>>x){
- highest=-999;
- len=x.length();
- len=len-L;
- for(int i=0;i<len;i++){
- tmp=x.substr(i,L);
- if(temp==tmp)continue;
- total=KMPSearch(tmp,x,i);
- if(total>highest){
- highest=total;
- temp=tmp;
- }
- }
- cout<<temp<<'\n';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement