String rotation, string rotation
Description: To specify a string, you must move several characters before it to the end of the string. For example, if you move the first three characters 'A', 'B', and 'c' of the string "abcdef" to the end of the string, the original string will become "defabc ". Write a function to implement this function.
Method 1: Brute Force Displacement
Defines the pointer s pointing to the string and sets the string length to n. First, implement LeftShiftOne (char * s, int n) to move a character to the end of the string, then, call m times to move m characters to the end of the string.
Reference code:
#include <bits/stdc++.h>using namespace std;void LeftShiftOne( char* s , int n ){ char t = s[0]; for( int i = 1 ; i < n ; i++ ) { s[i-1] = s[i]; } s[n-1] = t;}void LeftRotateString( char* s , int n , int m ){ while( m-- ) { LeftShiftOne( s , n ); }}int main(){ char str[]="abcdef"; cout<<str<<endl; LeftRotateString( str , 6 , 3 ); cout<<str<<endl;}
GCC running result:
Method 2: triplicate Technology
Take the above example to illustrate:
(1) divide the original characters into two parts: A and B (the division is based on moving m characters );
(2) flip the substring A and substring B. They are: "abc" ---> "CBA" "def" ---> "fed"
(3) Finally, flip the entire string to flip the string required by the question. The process is: "cbafed" ---> "defabc"
Reference code:
#include <bits/stdc++.h>using namespace std;void ReverseString( char *s , int from , int to ){ while( from < to ) { char t = s[from]; s[from++] = s[to]; s[to--] = t; }}void LeftRotateString( char *s , int n , int m ){ m%=n; ReverseString(s,0,m-1); ReverseString(s,m,n-1); ReverseString(s,0,n-1);}int main(){ char str[]="abcdef"; cout<<str<<endl; LeftRotateString(str,6,3); cout<<str<<endl;}
GCC running result: