BiruLyu
7/29/2017 - 9:25 PM

541. Reverse String II(#).java

public class Solution {
    private void reverse(char[] str, int start, int end) {
        while (start < end) {
            char temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
        }
    }
    public String reverseStr(String s, int k) {
        if (s == null || s.length() < 2) return s;
        int len = s.length();
        char[] str = s.toCharArray();
        for (int i = 0; i < len; i += 2 * k) {
            if (i + k > len) {
                reverse(str, i, len - 1);
            } else {
                reverse(str, i, i + k - 1);
            }
        }
        return new String(str);
    }
}