首页 > 代码库 > 旋转字符串

旋转字符串

旋转字符串 

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

样例

对于字符串 "abcdefg".

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

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

标签 
字符串处理
 
 1 class Solution {
 2 public:
 3     /**
 4      * @param str: a string
 5      * @param offset: an integer
 6      * @return: nothing
 7      */
 8     void rotateString(string &str,int offset){
 9         //wirte your code here
10         if(str.empty())
11             return;
12 
13         int off = offset % str.size();
14         if(off != 0)  {
15             string suffix(off+1, \0);
16             int i, j, size=str.size();
17             for(j=0,i=size-off; i<size; i++,j++) {
18                 suffix[j] = str[i];
19             }
20             for(i=size-off-1; i>=0; i--)  {
21                 str[i+off] = str[i];
22             }
23             for(i=0; i<off; i++)  {
24                 str[i] = suffix[i];
25             }
26         }
27     }
28 };

 

旋转字符串