8 旋转字符串

原题网址:http://www.lintcode.com/zh-cn/problem/rotate-string/#

给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)

样例

对于字符串 "abcdefg".

offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
挑战 

在数组上原地旋转,使用O(1)的额外空间

标签 
 
 1 #include <iostream>
 2 #include <vector>
 3 #include <math.h>
 4 #include <string>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 //方法一;
 9 void rotateString1(string &str, int offset)
10 {
11 
12     if (offset<=0||str.empty())
13     {
14         return ;
15     }
16     int size=str.size();
17     offset=offset%size;
18     vector<char> temp;
19 
20     for (int i=size-offset;i<size;i++)
21     {
22         temp.push_back(str[i]);
23     }
24     int last=size-1;
25     for (int j=size-offset-1;j>=0;j--)
26     {
27         str[last--]=str[j];
28     }
29     for (int m=0;m<offset;m++)
30     {
31         str[m]=temp[m];
32     }
33 }
34 
35 //方法二;
36 void rotateString2(string &str, int offset)
37 {
38 
39     if (offset<=0||str.empty())
40     {
41         return ;
42     }
43     int size=str.size();
44     offset=offset%size;
45 
46     //每次取出最后一个元素,移到第一个位置;
47     while(offset!=0)
48     {
49         char temp=str[size-1];
50 
51         for (int i=size-1;i>0;i--)
52         {
53             str[i]=str[i-1];
54         }
55         str[0]=temp;
56         offset--;
57     }
58 
59 }
原文地址:https://www.cnblogs.com/Tang-tangt/p/8634140.html