From e1fca55000f836b98a3dbc7d22e5ec0c266a048e Mon Sep 17 00:00:00 2001
From: Bruno Freitas Tissei <bft15@inf.ufpr.br>
Date: Mon, 29 Jul 2019 16:27:41 -0300
Subject: [PATCH] Add Booth's algorithm

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

diff --git a/algorithms/string/booth.cpp b/algorithms/string/booth.cpp
new file mode 100644
index 0000000..ca072de
--- /dev/null
+++ b/algorithms/string/booth.cpp
@@ -0,0 +1,40 @@
+/// Booth's Algorithm
+///
+/// Description:
+///   This algorithm finds the lexicographically minimal (or maximal) string
+/// rotation, that is, given a string $s$, the goal is to find a rotation of 
+/// $s$ possessing the lowest (or highest) lexicographical order among all 
+/// possible rotations.
+///
+/// Time: O(n)
+/// Space: O(n)
+
+string booth(string s) {
+  string S = s + s;
+  vector<int> f(S.size(), -1);
+
+  int k = 0;
+  for (int j = 1; j < S.size(); ++j) {
+    char sj = S[j];
+    int i = f[j - k - 1];
+
+    while (i != -1 && sj != S[k+i+1]) {
+      if (sj < S[k + i + 1]) // >: maximal
+        k = j - i - 1;
+      i = f[i];
+    }
+
+    if (sj != S[k+i+1]) {
+      if (sj < S[k]) // >: maximal
+        k = j;
+
+      f[j-k] = -1;
+    } else
+      f[j-k] = i + 1;
+  }
+
+  string ans(s.size(), 0);
+  for (int i = 0; i < s.size(); ++i)
+    ans[i] = S[k+i];
+  return ans;
+}
-- 
GitLab