26. Rotate string left (string)
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 ).
Ideas:
If the string is abcdefg, it must be left-handed. $ indicates the operation range. | indicates the axis to be rotated. The operation range is divided into two parts. Change the proximity of the smaller part to the larger part |. If the range is the same, it is directly exchanged.
1. $ AB | cdefg $
2 5
2. CD $ AB | EFG $
2 3
3. cdef & AB | G &
2 1
4. cdef & A | G & B
1 1
5. cdefgab is complete.
The Recursive Implementation of the code. But I don't know that I used int I in the loop and some auxiliary variables. Does it not meet the O (1) requirements of the auxiliary space?
# Include <stdio. h> # include <string. h> void swap (char * C1, char * C2) {char c = * C1; * C1 = * C2; * C2 = C;} void Exchange (char * S1, char * S2, int N) {for (INT I = 0; I <n; I ++) {swap (S1, S2); S1 ++; s2 ++ ;}} void rotate (char * In, int N, int Len) {n = n % Len; // determine whether the number of left-hand characters exceeds the string length int L = N, r = len-L; If (L <r) {len-= L; Exchange (in, in + L, L); rotate (in + l, l, Len);} else if (L> r) {Exchange (in + len-R, in + len-2 * R, R); Len-= r; rotate (in, len-R, Len);} else {Exchange (in, in + L, l) ;}} void leftrotate (char * In, int N) {rotate (in, N, strlen (in);} int main () {char s [] = "abcdefghi"; leftrotate (s, 10); Return 0 ;}
There is a clever idea on the Internet:
Http://blog.sina.com.cn/s/blog_60c8379d010144w9.html
Analysis: If the string is divided into two parts: AB, where a indicates the string to be moved to the end of the string, and B indicates the remaining part, we first reverse A and B, respectively, then, take the string as a whole to reverse the configuration. In this way, the first step is to get atbt and then get (atbt) T, that is, ba.
STL on the Internet to explain, haven't looked at the http://blog.csdn.net/zhoushuai520/article/details/7703368
[Programming question] rotating a string left ☆