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"
offset=4 => "defgabc"
offset=5 => "cdefgab"
offset=6 => "bcdefga"
offset=7 => "abcdefg"
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;
int len = str.length;
offset = offset % len;
char[] temp = new char[offset];
for (int i = 0; i < offset; i++) {
temp[i] = str[str.length-1-i];
}
for (int i = 0; i<str.length - offset; i++) {
str[str.length -1 - i] = str[str.length -1 - offset - i];
}
for (int i = 0; i < offset; i++) {
str[i] = temp[offset- 1 -i];
}
}
}
public class Solution {
public void rotateString(char[] str, int offset) {
int len = str.length;
char[] newstr = new char[len+1];
if (str == null || str.length == 0) return;
//modify offset if offset > length;
offset = offset % len;
for (int i = 0; i < offset; i++) {
newstr[i] = str[len-offset+i];
}
for (int i = offset; i < len; i++) {
newstr[i] = str[i-offset];
}
for (int i = 0; i < len; i++) {
str[i] = newstr[i];
}
return;
}
}
三步翻转法?O(1) extra memory
public class Solution {
public void rotateString(char[] str, int offset) {
if (str == null || str.length == 0) { return; }
int len = str.length;
offset = offset % len;
reverse(str, 0, len-offset-1);
reverse(str, len-offset, len-1);
reverse(str, 0, len-1); return; }
public void reverse(char[] str, int start, int end) {
while (start <= end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
}