LintCode【简单】8. 旋转字符串 。代码及思路

题目要求

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

样例

对于字符串 "abcdefg".

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

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

思路

考虑到挑战的条件是只用一个额外的空间,所以刚开始的思想是循环给定的offset次,每次都把字符串的0到 length-1位向后移一位,然后把之前记录的最后一位赋值给str[0],但是运行到87%出错了,如下:

Time Limit Exceeded

总耗时:  1342 ms
87% 数据通过测试.
输入
"timelimiterror"
1000000000
期望答案
"terrortimelimi"
提示
Your code ran too much time than we expected. Check your time complexity. Time limit exceeded usually caused by infinite loop if your time complexity is the best.

原因是没有考虑offset的长度,如果太大,就会造成时间的极大消耗。

修改好的代码如下,也考虑了str的length是0的情况。

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
        if(str.length() == 0) return;
        offset %= str.length();
        for(int i = 0; i < offset; i++){
            char temp = str[str.length() - 1];
            for(int j = str.length(); j > 0; j--){
                str[j] = str[j - 1];
            }
            str[0] = temp;
        }
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值