字符串旋转算法

字符串旋转算法,在很多地方都有提到过。主要有两种方法:

第一种,暴力移动。

第二种,大概都是参考编程珠玑上的字符串旋转算法。

这里有一个链接,http://crackprogramming.blogspot.com/2012/10/rotate-given-string-by-position.html

实现代码如下:

 1 #include <iostream>
 2 #include <cstring>
 3 
 4 
 5 
 6 using namespace std;
 7 
 8 void reverse(char *p,int begin,int end);
 9 void rotateString(char *p,int k);
10 int main()
11 {
12     char p[] = "helloworld";
13     cout << p << endl;
14     rotateString(p,3);
15     cout << p << endl;
16     return 0;
17 }
18 
19 
20 void reverse(char *p,int begin,int end)
21 {
22     int front=begin;
23     int back=end;
24     while(front<back)
25     {
26         p[front]=p[front]^p[back];
27         p[back]=p[front]^p[back];
28         p[front]=p[front]^p[back];
29         ++front;
30         --back;
31     }
32 }
33 
34 void rotateString(char *p,int k)
35 {
36     if(!p && !*p)
37     {
38         return;
39     }
40     int len=strlen(p);
41     k%=len;
42     reverse(p,0,len-1);
43     reverse(p,0,k-1);
44     reverse(p,k,len-1);
45 }
View Code

 

说明如下:

reverse方法是不使用临时空间的替换字符串方法。另外,这里的旋转字符,是按照顺时针方向进行旋转。后面有提到如何微调程序,将顺时针转换为逆时针。

下面是逆时针旋转的代码,请参考:

 1 #include <iostream>
 2 #include <cstring>
 3 
 4 
 5 
 6 using namespace std;
 7 
 8 void reverse(char *p,int begin,int end);
 9 void rotateString(char *p,int k);
10 int main()
11 {
12     char p[] = "helloworld";
13     cout << p << endl;
14     rotateString(p,3);
15     cout << p << endl;
16     return 0;
17 }
18 
19 
20 void reverse(char *p,int begin,int end)
21 {
22     int front=begin;
23     int back=end;
24     while(front<back)
25     {
26         p[front]=p[front]^p[back];
27         p[back]=p[front]^p[back];
28         p[front]=p[front]^p[back];
29         ++front;
30         --back;
31     }
32 }
33 
34 void rotateString(char *p,int k)
35 {
36     if(!p && !*p)
37     {
38         return;
39     }
40     int len=strlen(p);
41     k%=len;
42     k=len-k;
43     reverse(p,0,len-1);
44     reverse(p,0,k-1);
45     reverse(p,k,len-1);
46 }
View Code

 

这里就多了一行:k=len-k;

本文主要记录一下字符串旋转,关于习题,请好好参考一下上文链接。

转载于:https://www.cnblogs.com/lucy-lizhi/p/7365004.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值