leetcode-541-easy

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

思路一: 遍历每一个区间,区间内的字符做交换。用了 StringBuilder 来存储字符,发现耗时比用 char[] 多了好多

public String reverseStr(String s, int k) {
    StringBuilder sb = new StringBuilder(s);

    int i = 0;
    while (i < s.length()) {

        int begin = i;
        int end = Math.min(i + k - 1, s.length() - 1);

        while (begin < end) {
            char temp = sb.charAt(begin);
            sb.setCharAt(begin, sb.charAt(end));
            sb.setCharAt(end, temp);

            begin++;
            end--;
        }

        i += k*2;
    }

    return sb.toString();
}
posted @ 2022-10-24 17:53  iyiluo  阅读(25)  评论(0)    收藏  举报