给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地
旋转字符串(从左向右旋转)。
样例
样例 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
解题思路:
三次旋转法。先旋转offset部分,然后旋转剩余部分,最后旋转整体字符串。
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 == null || str.length == 0)
return;
offset = offset%str.length;
if(offset == 0)
return;
rotate(str, 0, str.length - 1 - offset); //前半部分旋转
rotate(str, str.length - offset, str.length - 1); //后半部分旋转
rotate(str, 0, str.length-1); //整体旋转
}
//翻转[i,j]之间的字符串
public void rotate(char[] str, int i, int j){
while(i < j){
swap(str, i++, j--);
}
}
public void swap(char[] str, int i, int j){
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}