Rotate string left

Source: Internet
Author: User

26. Rotate string left

Question:
Define the left rotation operation of the string: Move several characters before the string to the end of the string.

For example, the string abcdef is rotated two places to the left to obtain the string cdefab. Please implement the left rotation function of the string.
Requires that the complexity of the string operation with a length of n is O (n), and the auxiliary memory is O (1 ).

 

[Cpp] # include <iostream>
# Include <iomanip>
Using namespace std;
 
Void reverse (char * s, const int strl)
// Start with s and its length is strl
{
Int I, j;
Char tc;
For (I = 0, j = strl-1/* length minus one */; I <j; I ++, -- j)
{
Tc = s [I];
S [I] = s [j];
S [j] = tc;
}
}
Void Lshift (char * s, int m)
{
Const int slen = strlen (s );
Reverse (s, m );
Reverse (s + m, slen-m );
Reverse (s, slen );
}
 
Int main ()
{
Char s [] = "abcdefghijklmn ";
Lshift (s, 4 );
Cout <s <endl;
System ("pause ");
Return 0;
}

# Include <iostream>
# Include <iomanip>
Using namespace std;

Void reverse (char * s, const int strl)
// Start with s and its length is strl
{
Int I, j;
Char tc;
For (I = 0, j = strl-1/* length minus one */; I <j; I ++, -- j)
{
Tc = s [I];
S [I] = s [j];
S [j] = tc;
}
}
Void Lshift (char * s, int m)
{
Const int slen = strlen (s );
Reverse (s, m );
Reverse (s + m, slen-m );
Reverse (s, slen );
}

Int main ()
{
Char s [] = "abcdefghijklmn ";
Lshift (s, 4 );
Cout <s <endl;
System ("pause ");
Return 0;
}

Analysis: In the Lshift function, three reverse is called. The first two parts of the string are flipped separately, and the last one is flipped once. The result is left-hand m.

 

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.