Skip to content

Instantly share code, notes, and snippets.

@dipta10
Created November 13, 2018 09:41
Show Gist options
  • Select an option

  • Save dipta10/3b94ced5e21649275087721a09a6e741 to your computer and use it in GitHub Desktop.

Select an option

Save dipta10/3b94ced5e21649275087721a09a6e741 to your computer and use it in GitHub Desktop.
/*
* Name: Shift The String
* Created by Dipta Das on 09-11-18
* Problem Link: https://www.codechef.com/problems/TASHIFT
* solution: https://gist.github.com/dipta10/3b94ced5e21649275087721a09a6e741
* Editorial: https://discuss.codechef.com/questions/48550/tashift-editorial
*/
#include <bits/stdc++.h>
#include <stdio.h>
#define fin freopen("input", "r", stdin)
using namespace std;
vector<int> constructTempArray(string pattern) {
vector<int> lps(pattern.length());
int index = 0;
for (int i = 1; i < (int) pattern.length(); ) {
if (pattern[i] == pattern[index]) lps[i] = index + 1, ++index, ++i;
else {
if (index != 0) index = lps[index - 1];
else lps[i] = index, ++i;
}
}
return lps;
}
int KMPMultipleTimes (string text, string pattern) {
int best = 0, result = 0, ans = 0;
vector<int> lps = constructTempArray(pattern);
int j = 0, i = 0;
// i --> text, j --> pattern
while (i < (int) text.length()) {
if (text[i] == pattern[j]) ++i, ++j, best++;
else {
best = 0;
if (j != 0) j = lps[j - 1];
else ++i;
}
if (best > result) result = best, ans = i - j;
if (j == (int) pattern.length()) {
break;
}
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n; string a, b;
cin >> n >> a >> b;
b += b;
cout << KMPMultipleTimes(b, a) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment