Skip to content

Instantly share code, notes, and snippets.

@BigTape

BigTape/Z func Secret

Created February 11, 2024 09:53
Show Gist options
  • Save BigTape/2506b276900a6fea04d051bc4062c1f6 to your computer and use it in GitHub Desktop.
Save BigTape/2506b276900a6fea04d051bc4062c1f6 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void z_function (string s) {
int n = (int) s.length();
string str = s;
//reverse(str.begin(), str.end());
for (int i = 0; i < str.length() / 2; i++) {
swap(str[i], str[str.length() - 1 - i]);
}
s += '#';
s += str;
n = s.length();
//cout << s << '\n';
vector<int> z (n);
for (int i=str.length() + 1, l=0, r=0; i<n; ++i) {
if (i <= r)
z[i] = min (r-i+1, z[i-l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
//cout << "z[i] = " << z[i] << ' ' << s[i] << ' ' << "i + z[i] = " << i +z[i] << ' ' << s[i +z[i]] << '\n';
++z[i];
}
if (i+z[i]-1 > r)
l = i, r = i+z[i]-1;
//cout << z[i] << ' ';
}
int ans = 1;
for (int i = str.length() + 1; i < z.size(); i++) ans = max(ans, z[i]);
cout << ans;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string s;
cin >> s;
int n = s.length();
z_function(s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment