6. left rotation string
Title :
Defines the left rotation of a string : moves several characters in front of the string to the end of the string.
If the string abcdef left rotation 2 bit to get the string cdefab. Please implement the function of string left rotation.
The complexity of a string operation that requires time to be n is o (n), and auxiliary memory is O (1).
The first three ABCDEFG will be left-handed. First ABCDEFG->DEFABCG->DEFGBCA (Time is n-3)
Convert the problem to the previous left-hand side of the BCA. First BCA->ACB (time is 1)
Convert the problem to the previous left-hand spin of the CB. CB->BC (Time is 1)
All time complexity is 0 (n).
All problems are the letter 22 Exchange, and the auxiliary memory is O (1).
#include <iostream>#include<cstring>using namespacestd;Charstr[]="Abcdefghij";voidLeftrotatestring (intLeftintRightintN) { inttemp=right-Left ; for(inti=left+n;i<right;i++){ CharC=Str[i]; Str[i]=str[i-N]; Str[i-n]=B; } //output look at the results for(intI=0; i<right;i++) cout<<str[i];cout<<Endl; if(temp%n==0)return ; Else{ Left=right-N; N=n-temp%N; Leftrotatestring (Left,right,n); }}intMain () {intn=7; Leftrotatestring (0, strlen (str), n); return 0;}
Data structure and algorithm surface test questions 80 (26)