From 890f953c6cf7e27b3f34b9571107ac71e3734382 Mon Sep 17 00:00:00 2001
From: Bruno Freitas Tissei <bft15@inf.ufpr.br>
Date: Thu, 1 Feb 2018 15:14:14 -0200
Subject: [PATCH] Add KMP

Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br>
---
 string/kmp.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 44 insertions(+)
 create mode 100644 string/kmp.cpp

diff --git a/string/kmp.cpp b/string/kmp.cpp
new file mode 100644
index 0000000..f542fd4
--- /dev/null
+++ b/string/kmp.cpp
@@ -0,0 +1,44 @@
+/**
+ * Knuth-Morris-Pratt - KMP
+ *
+ * Complexity (Time): 
+ *   preprocess -> O(m)
+ *   search     -> O(n)
+ * Complexity (Space): O(n + m)
+ */
+
+int table[MAX];
+vector<int> occurs;
+
+// Build the table where table[i] is the longest prefix of patt[0..i] which is
+// also a sufix of patt[0..i]
+void preprocess(string patt) {
+  int i = 1, len = 0;
+
+  while (i < patt.size()) {
+    if (patt[i] == patt[len])
+      table[i++] = ++len;
+    else if (len)
+      len = table[len - 1];
+    else
+      table[i++] = 0;
+  }
+}
+
+// Search for occurrences of patt in txt and add indexes of matches to occurs
+void search(string patt, string txt) {
+  int i = 0, j = 0;
+
+  while (i < txt.size()) {
+    if (patt[j] == txt[i])
+      i++, j++;
+
+    if (j == patt.size()) {
+      occurs.push_back(i - j); // Pattern found at (i - j)
+      j = table[j - 1];
+    } else if (i < txt.size() && patt[j] != txt[i]) {
+      if (j) j = table[j - 1];
+      else i++;
+    }
+  }
+}
-- 
GitLab