Rotate String
Source
Given a string and an offset, rotate string by offset. (rotate from left to right)
Example
Given "abcdefg".
offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
Challenge
Rotate in-place with O(1) extra memory.
Java
public class Solution {
public void rotateString(char[] str, int offset) {
if(str==null || str.length==0) return;
int len = str.length;
offset %= len;
reverse(str, 0, len-1);
reverse(str, 0, offset-1);
reverse(str, offset, len-1);
}
public void reverse(char[] str, int left, int right){
while(left<right){
char tmp = str[left];
str[left]=str[right];
str[right]=tmp;
left++;
right--;
}
}
}