From a3590b78bbbe60ad8a40339f6d33b450bdcebf8d Mon Sep 17 00:00:00 2001
From: Bruno Freitas Tissei <bft15@inf.ufpr.br>
Date: Wed, 8 May 2019 18:41:14 -0300
Subject: [PATCH] Fix kmp

Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br>
---
 algorithms/string/kmp.cpp | 82 ++++++++++++++++++++-------------------
 1 file changed, 42 insertions(+), 40 deletions(-)

diff --git a/algorithms/string/kmp.cpp b/algorithms/string/kmp.cpp
index 654f710..76357a3 100644
--- a/algorithms/string/kmp.cpp
+++ b/algorithms/string/kmp.cpp
@@ -5,47 +5,49 @@
 ///   search     -> O(n)
 /// Complexity (Space): O(n + m)
 
-int table[MAX];
-
-/// Builds the table where table[i] is the longest prefix of
-/// patt[0..i] which is
-/// also a sufix of patt[0..i]
-/// @param patt pattern to be found
-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;
+struct KMP {
+  string patt;
+  vector<int> table;
+
+  KMP(string patt) :
+    patt(patt), table(patt.size())
+  { preprocess(); }
+
+  /// Builds the table where table[i] is the longest prefix of
+  /// patt[0..i] that is also a sufix of patt[0..i].
+  void preprocess() {
+    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;
+    }
   }
-}
-
-/// Searches for occurrences of patt in txt and add indexes of 
-/// matches to occurs
-/// @param patt pattern to be found
-/// @param txt text
-void search(string patt, string txt) {
-  int i = 0, j = 0;
-  vector<int> occurs;
-
-  while (i < txt.size()) {
-    if (patt[j] == txt[i])
-      i++, j++;
-
-    if (j == patt.size()) {
-
-      // Pattern found at (i - j)
-      occurs.push_back(i - j);
-      j = table[j - 1];
-    } else if (i < txt.size() && patt[j] != txt[i]) {
-      if (j > 0) 
+
+  /// Searches for occurrences of patt in txt and return vector
+  /// of the indices of occurrence.
+  /// @param txt text
+  vector<int> search(const string &txt) {
+    int i = 0, j = 0;
+    vector<int> occurs;
+
+    while (i < txt.size()) {
+      if (patt[j] == txt[i])
+        i++, j++;
+
+      if (j == patt.size()) {
+        occurs.push_back(i - j);
         j = table[j - 1];
-      else 
-        i++;
+      } else if (i < txt.size() && patt[j] != txt[i]) {
+        if (j > 0) j = table[j - 1];
+        else i++;
+      }
     }
+
+    return occurs;
   }
-}
+};
-- 
GitLab