LeetCode 541. Reverse String II

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.

Example 1:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Example 2:

Input: s = "abcd", k = 2
Output: "bacd"

Constraints:

  • 1 <= s.length <= 104
  • s consists of only lowercase English letters.
  • 1 <= k <= 104

这题给了一个string和一个k,把这个string分成2k长度的block,每个block里reverse前k个。如果最后一个block里只有不到k个,就全reverse,如果比k多但是比2k少,就reverse前k个(其实是consistent的)。

第一反应就是stringbuilder + 一个for loop,每2k个处理一次,每次先reverse前k个,再复制后k个就行。这样写起来代码很直观,但是不是特别优雅,而且要处理最后一个block的长度问题比较tricky,也是试了好几个test case才写好,把自己绕进去了……

class Solution {
    public String reverseStr(String s, int k) {
        char[] charArray = s.toCharArray();
        int len = s.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i += 2 * k) {
            int maxIndex = Math.min(i + k, len);
            for (int j = maxIndex - 1; j >= i; j--) {
                sb.append(charArray[j]);
            }
            maxIndex = Math.min(i + 2 * k, len);
            for (int j = i + k; j < maxIndex; j++) {
                sb.append(charArray[j]);
            }
        }
        return sb.toString();
    }
}

然后是一个特别优雅的解法,并不需要用到stringbuilder,直接一个while loop + swap搞定。相当于就是每隔2k个,计算出需要reverse的最大的index,然后swap里面的元素。

class Solution {
    public String reverseStr(String s, int k) {
        char[] charArray = s.toCharArray();
        int len = s.length();
        int i = 0;
        while (i < len) {
            int j = Math.min(i + k - 1, len - 1);
            swap(charArray, i, j);
            i += 2 * k;
        }
        return new String(charArray);
    }

    private void swap(char[] array, int i, int j) {
        char temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

你可能感兴趣的:(LeetCode,leetcode)