String rotation, string rotation

Source: Internet
Author: User

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:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.