[LintCode] Rotate String [周而复始]

375 查看

Problem

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.

Note

完成challenge,三步翻转法。见Sol.2。

Solution

1.

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--;
        }
    }
}