Rotate String

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"

Solution:

For the example offset=3 => “efgabcd”.
First reverse “abcd” in “abcdefg”, we can get “dcbaefg”.
Then reverse “efg” in “dcbaefg”, we can get “dcbagfe”.
Finally, reverse the whole string “dcbagfe”, we can get “efgabcd”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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; //Important row

reverse(str, 0, str.length - 1 - offset);
reverse(str, str.length - offset, str.length - 1);
reverse(str, 0, str.length - 1);
}

public void reverse(char[] str, int start, int end){
for (int i = start, j = end; i < j; i++, j--){
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}