From 533022b31738ee2bd0708838f71a0a8a6021516b Mon Sep 17 00:00:00 2001
From: Bruno Freitas Tissei <bft15@inf.ufpr.br>
Date: Sun, 5 May 2019 16:49:46 -0300
Subject: [PATCH] Add Z-function

Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br>
---
 algorithms/graph/topological_sort.cpp |  2 +-
 algorithms/string/z-function.cpp      | 29 +++++++++++++++++++++++++++
 2 files changed, 30 insertions(+), 1 deletion(-)
 create mode 100644 algorithms/string/z-function.cpp

diff --git a/algorithms/graph/topological_sort.cpp b/algorithms/graph/topological_sort.cpp
index 04ca9e0..e19c8de 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 0000000..9ab2ed7
--- /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;
+  }
+};
-- 
GitLab