Title Description
Given a string, it is required to move several characters in front of the string to the end of the string, such as the string "ABCdef" before the 2 characters ' a ' and ' B ' moved to the end of the string, so that the original string into the string "Cdefab". Write a function that requires an O (n) time complexity for a string operation of length n and an O (1) space complexity.
2:3-Step inversion method for analysis and solution
For this problem, think for a different angle.
Dividing a string into X and y two parts, defining a reversal operation on each part of the string, such as x^t, which reverses all the characters of x (for example, x= "abc", then x^t= "CBA"), then the following conclusion is obtained: (x^ty^t) ^t=yx, obviously solves the problem of string inversion.
For example, String abcdef, to let def flip to the head of ABC, just follow these 3 steps:
- First of all, the original string is divided into two parts, namely X:abc,y:def;
- The X is reversed, x->x^t,:abc->cba; Y is reversed, y->y^t, that is: def->fed.
- Reverse the results of the above steps to get the string x^ty^t, that is, the inverse of the string cbafed two parts (CBA and fed) to give reversal, cbafed get DEFABC, formally expressed as (x^ty^t) ^t=yx, which realizes the entire reversal.
C language version:
#include <stdio.h> #include <string.h>void reversestring (char* s,int from,int to) {when (from < to) c1/>{ char t = s[from]; s[from++] = s[to]; s[to--] = t; } } void Leftrotatestring (char* s,int n,int m) { m%= n; To move the left more than n bits, then the%n is equivalent to reversestring (s, 0, m-1);//Invert [0..m-1], apply to the example above, is x->x^t, that is ABC->CBA ReverseString (S, M, n-1); Invert [M.. N-1], such as y->y^t, i.e. def->fed reversestring (s, 0, n-1);//Invert [0..n-1], i.e. the entire reversal, (x^ty^t) ^t=yx, CBAFED->DEFABC 。 }int Main () { char a[]= "Hello World"; Leftrotatestring (A,strlen (a), 2); printf ("%s\n", a);}
Go language version:
Package Mainimport ( "FMT") func reversestring (s []byte,from int,to int) { for{ T:=s[from] s[from]=s[ To] s[to]=t from++ to-- if from>to{ break } }}func leftrotatestring (s []byte,n int , M int) { m%=n reversestring (s,0,m-1) reversestring (s,m,n-1) reversestring (s,0,n-1)}func main () { a:=[]byte ("Hello World") leftrotatestring (A,len (a), 2) FMT. Println (String (a))}
PHP Version:
<?phpfunction reversestring (& $str, $from, $to) {while ($from < $to) { $t = $str [$from]; $str [$from ++]= $str [$to]; $str [$to--]= $t; } } Function leftrotatestring (& $str, $n, $m) { $m%= $n;//If the length of the first few characters is greater than the string length reversestring ($str, 0, $m-1); ReverseString ($str, $m, $n-1); ReverseString ($str, 0, $n-1);} $a = "Hello World"; Leftrotatestring ($a, strlen ($a), 2); Echo $a. " \ n ";
[Daily] Algorithm-rotation string-three-step flip method