三步反轉法:先將前m個字符反轉,再反轉後面(n-m)個字符, 最後反轉整個字符串。code
例如:abcdef ,n=6, m=3,cba + fed =>defabc字符串
void ReverseString( char* s, int from, int to){ while( from < to){ char temp = s[from]; s[from++] = s[to]; s[to--] = temp; } }
m==n,m%=n => m==0, while
m<n , m==mco
void LeftRotate( char* s, int n, int m){ if(m>n) ; else { m%=n; ReverseString( s, 0, m-1); ReverseString( s, m, n-1); ReverseString( s, 0, n-1); } }