Question
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"
Idea
- mod N operation gives you the actual steps needed to move without meaningless repetition
public class Solution {
/**
* @param str: An array of char
* @param offset: An integer
* @return: nothing
*/
public void rotateString(char[] str, int offset) {
if (str.length == 0) return;
char[] res = new char[str.length];
int moves = offset % str.length;
for (int originalPos = 0; originalPos < str.length; originalPos++) {
int targetPos = str.length > originalPos + moves
? originalPos + moves
: (moves + originalPos) % str.length;
res[targetPos] = str[originalPos];
}
for (int i = 0; i < str.length; i++)
str[i] = res[i];
}
}