描述
给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
您在真实的面试中是否遇到过这个题?
是
样例
对于字符串 "abcdefg"
.
offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
挑战
在数组上原地旋转,使用O(1)的额外空间
思路比较简单,新建一个偏移量大小的数组,储存旋转部分的字符串,然后将剩余字符串后移,最后将需要旋转的字符串补上。
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){
string t_string;
offset=offset%(str.length());
for (int i = 0; i < offset; i++) {
t_string[offset - 1 - i] = str[str.length() - 1 - i];
}
for (int i = 0; i < (str.length() - offset); i++) {
str[str.length() - 1 - i] = str[str.length() - 1 - offset - i];
}
for (int i = 0; i < offset; i++) {
str[i] = t_string[i];
}
}
}
};