-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfindstr.cpp
More file actions
93 lines (87 loc) · 1.48 KB
/
findstr.cpp
File metadata and controls
93 lines (87 loc) · 1.48 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include<iostream>
#include<vector>
#include<string>
#include<cstdio>
#include<algorithm>
using namespace std;
// Z-Algorithm for Pattern Matching
// O(n+m)
inline vector<int> calculateZ(string inp)
{
int len = inp.length();
vector<int> Z(len);
int left = 0;
int right = 0;
for(int k = 1; k < len; k++)
{
if(k > right)
{
left = right = k;
while(right < len && inp[right] == inp[right-left])
{
right++;
}
Z[k] = right - left;
right--;
}
else
{
int k1 = k - left;
// inside the Z-Box
if(Z[k1] < right-k+1)
{
Z[k] = Z[k1];
//if the value is inside the Z-box then copy it
}
else
{
// otherwise do more comparisons
left = k;
while(right < len && inp[right] == inp[right-left])
{
right++;
}
Z[k] = right-left;
right--;
}
}
}
return Z;
// Z[i] denotes the length of the longest substring starting from i which is also the prefix of the string.
}
int main()
{
while(1)
{
string s; cin >> s;
int len = s.length();
if(s[0] == '*')
return 0;
vector<int> z = calculateZ(s);
int sc = 0;
for(int i = 0;i < z.size(); i++)
if(z[i])
if(z[i] == len - i && len%(len-i) == 0)
sc = len-i;
if(sc == 0)
{
cout << 1 << "\n";
continue;
}
string t = s.substr(0,sc);
int ok = 1;
int k = 0;
for(int i = 0;i < len; i++)
{
if(s[i] != t[k++])
ok = 0;
if(k == sc)
k =0;
}
if(ok)
cout << len/sc << "\n";
else
cout << 1 << "\n";
}
return 0;
}