给定一个字符串str和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。
三次颠倒
根据偏移量将数组划分为两部分 对这两部分分别颠倒(双指针首尾互换)
再将数组整体颠倒
public class Solution {
/**
* @param str: An array of char
* @param offset: An integer
* @return: nothing
*/
public void rotateString(char[] str, int offset) {
int n = str.length;
if(n > 0){
offset = offset % n;
reverse(str, 0, n - offset - 1);
reverse(str, n - offset, n - 1);
reverse(str, 0, n - 1);
}
}
public void reverse(char[] str, int begin, int end){
int left = begin, right = end;
while(left < right){
char temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
}
}