diff --git a/algorithms/string/booth.cpp b/algorithms/string/booth.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca072deea1dcf2dfb2351ee95b9fef03bf485953 --- /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; +}