File tree Expand file tree Collapse file tree 1 file changed +32
-3
lines changed Expand file tree Collapse file tree 1 file changed +32
-3
lines changed Original file line number Diff line number Diff line change 11// Z-Algorithm
22// z[i] is length of prefix starting from i
3- int z[N];
4- void go (string s){
3+
4+ // always pass stirng by reference, weird how it got me SIGSEGV in a Codechef problem
5+ // https://codeforces.com/blog/entry/77906
6+ vector<int > go (const string &s){
7+ vector<int > z (s.size (), 0 );
58 int i, n = s.size (), L = 0 , R = 0 ;
69 z[0 ] = 0 ;
710 Fo (i, 1 , n){
@@ -22,5 +25,31 @@ void go(string s){
2225 }
2326 }
2427 }
25-
28+
29+ return z;
2630}
31+
32+
33+ // another implementation
34+ template <typename T>
35+ vector<int > z_function (int n, const T &s) {
36+ vector<int > z (n, n);
37+ int l = 0 , r = 0 ;
38+ for (int i = 1 ; i < n; i++) {
39+ z[i] = (i > r ? 0 : min (r - i + 1 , z[i - l]));
40+ while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
41+ z[i]++;
42+ }
43+ if (i + z[i] - 1 > r) {
44+ l = i;
45+ r = i + z[i] - 1 ;
46+ }
47+ }
48+ return z;
49+ }
50+
51+ template <typename T>
52+ vector<int > z_function (const T &s) {
53+ return z_function ((int ) s.size (), s);
54+ }
55+
You can’t perform that action at this time.
0 commit comments