21左轉字符串
一 問題描述
對字符串進行左旋轉操作,比如字符串為 cdefab ,執行左旋轉2操作之后,字符串變為efabcd 。要求使用o(n)的時間復雜度 和o(1)的空間完成。
考慮之前實現的字符串中單詞翻轉問題 I am a student. 問題設單詞劃分為AB 兩部分 ,則BA = (AT BT)T。
即先對A部分逆轉,再對B部分逆轉,最后再對上述中間結果,進行逆轉 。
二 代碼描述
#include <iostream>
using namespace std ;
void reverse(char * l , char * h) //實現逆轉

{
if(l == 0 || h == 0)
return ;
while(l < h)

{
swap(*l ,*h) ;
l++ ;
h-- ;
}
}
void leftreverse(char * s, int k , int n)

{
if(k > n )
return ;
char * t = s + k - 1;
char * end = s + n -1 ;
reverse(s , t) ;
reverse(t + 1 , end) ;
reverse(s , end) ;
}
int main()

{
char s[100] = "dsadsda" ; //char *s 為字符串常量
leftreverse(s , 3 , strlen(s)) ;
cout<<s<<endl;
system("pause") ;
return 0 ;
}