diff --git a/algorithms/graph/topological_sort.cpp b/algorithms/graph/topological_sort.cpp index 04ca9e0560d0c9209c0395da6de424390c34771f..e19c8de4e43f716100f1e0a61182b314428cc77a 100644 --- a/algorithms/graph/topological_sort.cpp +++ b/algorithms/graph/topological_sort.cpp @@ -38,7 +38,7 @@ struct TopologicalSort { /// Returns whether graph contains cycle or not. /// @param[out] tsort topological sort of the graph - bool topological_sort(vector<int> &tsort) { + bool run(vector<int> &tsort) { init(); bool cycle = false; diff --git a/algorithms/string/z-function.cpp b/algorithms/string/z-function.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ab2ed79eebf4da3ba0650f2faa32daea4a517a3 --- /dev/null +++ b/algorithms/string/z-function.cpp @@ -0,0 +1,29 @@ +/// 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; + } +};