Skip to content
Snippets Groups Projects
Commit 533022b3 authored by Bruno Freitas Tissei's avatar Bruno Freitas Tissei
Browse files

Add Z-function

parent 4ea210c9
Branches
No related tags found
No related merge requests found
...@@ -38,7 +38,7 @@ struct TopologicalSort { ...@@ -38,7 +38,7 @@ struct TopologicalSort {
/// Returns whether graph contains cycle or not. /// Returns whether graph contains cycle or not.
/// @param[out] tsort topological sort of the graph /// @param[out] tsort topological sort of the graph
bool topological_sort(vector<int> &tsort) { bool run(vector<int> &tsort) {
init(); init();
bool cycle = false; bool cycle = false;
......
/// Z-function
///
/// Complexity (time): O(n)
/// Complexity (space): O(n)
struct ZFunction {
/// Computes z-function of a string and returns it.
/// @param s input string
vector<int> run(string s) {
int n = (int) s.length();
vector<int> z(n);
int l = 0, r = 0;
for (int i = 1; i < n; ++i) {
if (i <= r)
z[i] = min(r - i + 1, z[i - l]);
for (; i + z[i] < n && s[z[i]] == s[i + z[i]]; ++z[i]);
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
};
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment