给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。
样例
样例 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
public class Solution {
/**
* @param str: An array of char
* @param offset: An integer
* @return: nothing
*/
public void rotateString(char[] str, int offset) {
// write your code here
if (str.length <= 1) return;
offset = offset % str.length;
int len = str.length;
for (int j = 0; j < offset; j++) {
char temp = str[str.length - 1];
for (int i = len-1; i >0; i--) {
str[i] = str[i-1];
}
str[0]=temp;
}
}
}