您的位置:首页 > 其它

左旋转字符串

2012-09-28 08:54 204 查看
问题描述:左旋转字符串。

input:abc 2 output:cab

intput:abcd 2 output :cdab

代码:

1 #include <iostream>

2 using namespace std;

3

4 void LeftRotateString(char **str,const int m)

5 {

6 if(m==0) return;

7 int length=strlen(*str);

8 char *ptr=*str;

9 int i=0,j=0,last=length-1,lastpos=0;

10 for(;i<m;i++)

11 {

12 char temp=ptr[i];

13 for(j=0;j*m+i+m<length;j++)

14 {

15 ptr[j*m+i]=ptr[j*m+i+m];

16 }

17 if(i==0) lastpos=j*m;

18 ptr[j*m+i]=temp;

19 }

20 int lastm=m-(length-lastpos);

21 int start=lastpos-lastm;

22 if(lastm!=0)

23 {

24 ptr=*str+start;

25 LeftRotateString(&ptr,lastm);

26 }

27

28 }

29 int main()

30 {

31 char str[100];

32 char *temp=NULL;

33 int n;

34 while(1)

35 {

36 cin>>str;

37 temp=str;

38 cin>>n;

39 LeftRotateString(&temp,n);

40 cout<<str<<endl;

41 }

42 return 0;

43 }

Output:

[root@localhost Test]# ./a.out

abc

2

cab

abcd

2

cdab

abcd

3

dabc

abcdefg

4

efgabcd

abc

1

bca
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: