-
Notifications
You must be signed in to change notification settings - Fork 0
/
findsr.cpp
50 lines (41 loc) · 797 Bytes
/
findsr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void print_vec(vector<T> v) {
for (int i=0; i<v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
}
vector<int> compute_prefix_kmp(string a) {
vector<int> pi(a.length());
pi[0] = 0;
for (int i=1; i < a.length(); i++) {
int j = pi[i-1];
while (j>0 && a[i]!=a[j]) {
j = pi[j-1];
}
if (a[i] == a[j]) {
j++;
}
pi[i] = j;
}
return pi;
}
int main() {
string input;
while(cin >> input && input != "*") {
vector<int> pi = compute_prefix_kmp(input);
// print_vec(pi);
int len = input.length();
int max = pi[len-1];
int period_k = 1;
// Find the period of the string
if (len % (len-max) == 0) {
period_k = len/(len-max);
}
cout << period_k << endl;
}
return 0;
}