题目要求
给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
样例
对于字符串 "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;
}
}
};