# Include <iostream> # include <cstdlib> # include <string> # include <queue> using namespace STD;/** design Algorithm , Shifts the right K-Bit of an array containing n elements, requires the time complexity to O (n) * // ** solution 1: store the array in a queue, shift K to the right of the loop, which is equivalent to shift the N-K to the left of the loop * For the queue, move one to the left of the loop, which is equivalent to taking out the first element of the queue and then inserting the end of the queue */class solution {PRIVATE: String STR; // source string, string result input by the keyboard; // converted string queue <char> q; // auxiliary queue public: solution () {CIN> STR; string:: iterator it;/** convert the input string to a queue */For (IT = Str. begin (); it! = Str. end (); It ++) {q. push (* It); // Insert the element to the end of the team} void justdoit (int K) {int I; char t; int n = Q. size (); // Number of retrieved queue elements/** parameter judgment */If (k <0) {cerr <"parameter error! "<Endl; exit (1) ;}/ ** when k> N, the loop shifts K places to the right, which is equivalent to the shift K % N places to the right of the loop */K % = N; for (I = 1; I <= n-k; I ++) {T = Q. front (); // retrieve the first element Q. pop (); // pop up the first element (queue head out, tail in) Q. push (t);}/** generate result string */for (I = 1; I <= N; I ++) {T = Q. front (); q. pop (); Result + = T ;}} void show () const {cout <result <Endl ;}}; void main () {solution s; S. justdoit (4); S. show ();}
# Include <iostream> # include <cstdlib> # include <string> # include <queue> using namespace STD;/** design an algorithm, shifts the right K-Bit of an array containing n elements, requiring the time complexity to O (n) * // ** solution 2: store the array as a string, the transpose method is used to solve * assume that the string is XY, and Y is the substring to be shifted to the right. The result after moving should be Yx *, then (Yx) = (xtyt) T */class solution {PRIVATE: String STR; // source string, input string result by keyboard; // converted string public: solution () {CIN> STR ;} /** reverse the string s from pointer I to pointer J */void swap (string & S, int I, Int J) {char t; while (I <j) {T = S [I]; s [I] = s [J]; s [J] = T; I ++; j -- ;}} void justdoit (int K) {int n = Str. size ();/** parameter judgment */If (k <0) {cerr <"parameter error! "<Endl; exit (1) ;}/ ** when k> N, the loop shifts K places to the right, which is equivalent to the shift K % N places to the right of the loop */K % = N; result = STR; swap (result, 0, n-k-1); swap (result, n-k, n-1); swap (result, 0, n-1);} void show () const {cout <result <Endl ;}}; void main () {solution s; S. justdoit (4); S. show ();}
Test: