題目描述:給定一個字符串,要求將字符串前面的若干個字符移動到字符串的尾部。例如,將字符串"abcdef"的前3個字符'a'、'b'、'c'移動到字符串的尾部,那麼原字符串將變成"defabc"。請寫一個函數實現此功能。
方法一:蠻力移位
定義指向字符串的指針s,設字符串長度為n,首先實現LeftShiftOne(char *s ,int n)將一個字符移動到字符串的最後,然後調用m次實現將m個字符移動到字符串末尾
參考代碼:
#include <bits/stdc++.h>
using namespace std;
void LeftShiftOne( char* s , int n )
{
char t = s[0];
for( int i = 1 ; i < n ; i++ )
{
s[i-1] = s[i];
}
s[n-1] = t;
}
void LeftRotateString( char* s , int n , int m )
{
while( m-- )
{
LeftShiftOne( s , n );
}
}
int main()
{
char str[]="abcdef";
cout<<str<<endl;
LeftRotateString( str , 6 , 3 );
cout<<str<<endl;
}
GCC運行結果:

方法二:三步翻轉
拿上面的例子來說明:
(1)將原來的字符劃分為兩個部分A和B(劃分依據為所移動m個字符);
(2)將子字符串A和B進行翻轉操作; 分別為:"abc"--->"cba" "def"--->"fed"
(3)最後將整體字符串進行翻轉操作,從而實現題目要求的字符串翻轉. 過程為: "cbafed"--->"defabc"
參考代碼:
#include <bits/stdc++.h>
using namespace std;
void ReverseString( char *s , int from , int to )
{
while( from < to )
{
char t = s[from];
s[from++] = s[to];
s[to--] = t;
}
}
void LeftRotateString( char *s , int n , int m )
{
m%=n;
ReverseString(s,0,m-1);
ReverseString(s,m,n-1);
ReverseString(s,0,n-1);
}
int main()
{
char str[]="abcdef";
cout<<str<<endl;
LeftRotateString(str,6,3);
cout<<str<<endl;
}
GCC運行結果:
