Skip to content
Snippets Groups Projects
Commit e1fca550 authored by Bruno Freitas Tissei's avatar Bruno Freitas Tissei
Browse files

Add Booth's algorithm

parent 0e7e025d
No related branches found
No related tags found
No related merge requests found
/// 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;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment