左旋转字符串

来源:互联网 发布:mac储存空间怎么查看 编辑:程序博客网 时间:2024/04/30 05:35

问题描述:左旋转字符串。

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

原创粉丝点击