左旋转字符串
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
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
相关文章推荐
- 字符串是否互为旋转
- 字符串旋转检测算法
- 字符串的旋转
- 字符串左右旋转问题
- 左旋转字符串
- 左旋转字符串新思路
- 8.旋转字符串
- 【九度OJ1362】|【剑指offer42】左旋转字符串
- [字符串]左旋转字符串
- [置顶] 剑指offer:第42题反转单词顺序VS左旋转字符串
- 微软100题(26)左旋转字符串
- (剑指offer)左旋转字符串 扑克牌顺子
- LintCode之旋转字符串
- 坑.51nod-1347 旋转字符串
- java实现字符串左旋转
- 26 左旋转操作:把字符串前面的若干个字符移动到尾部
- 程序员面试题精选100题(21)-左旋转字符串
- 剑指offer面试题之左旋转字符串
- 判断一个字符串是否为另外一个字符串旋转之后的字符串。 例如:给定s1 = AABCD和s2 = BCDAA,返回1,给定s1=abcd和s2=ACBD,返回
- 左旋转字符串