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 left-byte 2 to get the string "cdefab ". Please implement the left rotation function of the string.
Requires O (n) for the complexity of string operations with a length of n, and the auxiliary memory is O (1 ).
Analysis:
The difficulty of this question is that the secondary memory can only use O (1), which is equivalent to only replacing the characters in the string. To move the string, m * n replacement operations are required, this complexity also comes up, O (n * n ).
You can only think about skills.
The implementation is as follows:
#include
#include
using namespace std;void reverse(char* str, int i, int j){ while( i < j) { char chr = str[i]; str[i] = str[j]; str[j] = chr; i ++; j --; }}void leftRotate(char* srcstr, int k){ int len = strlen(srcstr); if(len <= 1) return; k = k%len; reverse(srcstr, 0, k - 1); reverse(srcstr, k, len -1); reverse(srcstr, 0, len -1);}int main(){ char str[] = "abcdef"; cout << "string: " << str << endl; leftRotate(str, 2); cout << "rotate string, 2: " << str << endl; return 0;}
The output result is as follows:
String: abcdef
Rotate string, 2: cdefab