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.