字符串旋转算法

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

第一种,暴力移动。

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

这里有一个链接,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;

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

posted on 2017-08-15 14:42  ^~~^  阅读(238)  评论(0编辑  收藏  举报

导航