From 5c830ee9eba42d4fd474932364ff3434e04e3af8 Mon Sep 17 00:00:00 2001 From: Ashish Gupta Date: Fri, 26 Jun 2020 22:07:01 +0530 Subject: [PATCH] Create String Rotation (Booth's Algorithm).cpp --- String Rotation (Booth's Algorithm).cpp | 30 +++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 String Rotation (Booth's Algorithm).cpp diff --git a/String Rotation (Booth's Algorithm).cpp b/String Rotation (Booth's Algorithm).cpp new file mode 100644 index 0000000..b1aef79 --- /dev/null +++ b/String Rotation (Booth's Algorithm).cpp @@ -0,0 +1,30 @@ +//Returns the lexicographically least rotation of string + +string least_rotation(string s) +{ + s += s; + vector 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]) + k = j - i - 1; + i = f[i]; + } + if(sj != s[k + i + 1]) + { + if(sj < s[k]) + k = j; + f[j - k] = -1; + } + else + f[j - k] = i + 1; + } + return s.substr(k, s.size() / 2); +} + +//Problem 1: https://www.codechef.com/BIT32020/problems/BIT3B