LintCode8. 旋转字符串

 

8. 旋转字符串

中文English

给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。

样例

样例 1:

输入:  str="abcdefg", offset = 3
输出:  str = "efgabcd"	
样例解释:  注意是原地旋转,即str旋转后为"efgabcd"

样例 2:

输入: str="abcdefg", offset = 0
输出: str = "abcdefg"	
样例解释: 注意是原地旋转,即str旋转后为"abcdefg"

样例 3:

输入: str="abcdefg", offset = 1
输出: str = "gabcdef"	
样例解释: 注意是原地旋转,即str旋转后为"gabcdef"

样例 4:

输入: str="abcdefg", offset =2
输出: str = "fgabcde"	
样例解释: 注意是原地旋转,即str旋转后为"fgabcde"

样例 5:

输入: str="abcdefg", offset = 10
输出: str = "efgabcd"	
样例解释: 注意是原地旋转,即str旋转后为"efgabcd"

挑战

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

说明

原地旋转意味着你要在s本身进行修改。你不需要返回任何东西。

注意事项

offset >= 0
the length of str >= 0
Make changes on the original input data

C++实现:

class Solution {
public:
    /**
     * @param str: An array of char
     * @param offset: An integer
     * @return: nothing
     */
    void rotateString(string &str, int offset) {
        // write your code here

       std::vector<char> str_char;
       int strLenght = 0;
       int offset_true = 0;
      // int i = 0;
       while(str[strLenght] != '\0'){
          // i++;
          str_char.push_back(str[strLenght]);
          strLenght++;
       }
       if(strLenght == 0)
          return;
       
       offset_true = offset%strLenght;
       
     /*  for(int j=0;j<offset_true;j++)
         {
             
         }*/ //reverse(str_char.begin(),str_char.end());
        int m = 0;
        for(int k=strLenght-offset_true;k<str_char.size();k++){
            str[m] = str_char[k];
            m++;
        }
        for(int f=0;f<str_char.size() - offset_true;f++){
            str[m] = str_char[f];
            m++;
        }
        return;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值