Given a string s and an integer k, you need to reverse the first k characters every 2k characters from the beginning of the string.
如果剩余字符少于 k 个,则将剩余字符全部反转。
如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
Example:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
prompt:
该字符串只包含小写英文字母。
给定字符串的长度和 k 在 [1, 10000] 范围内。
The general meaning of this question is to reverse k every k, and all reverse
when there are not enough k. At the beginning of this question, the idea was wrong. I wanted to use a counter to count. After re-starting the reversal program, start the reversal program to reverse the k reversals.
This kind of thinking is too complicated and troublesome.
The following is the idea of the solution.
We directly flip each 2k character block.
Each block starts at a multiple of 2k, which is 0, 2k, 4k, 6k, …. One thing to note is: if there are not enough characters, we don't need to flip this block.
In order to flip the block of characters from i to j, we can swap the characters located at i++ and j--.
class Solution {
public String reverseStr(String s, int k) {
char[] a = s.toCharArray();
for (int start = 0; start < a.length; start += 2 * k) {
int i = start, j = Math.min(start + k - 1, a.length - 1);
while (i < j) {
char tmp = a[i];
a[i++] = a[j];
a[j--] = tmp;
}
}
return new String(a);
}
}
Author: LeetCode
link: https: //leetcode-cn.com/problems/reverse-string-ii/solution/fan-zhuan-zi-fu-chuan-ii-by-leetcode/
Source: stay button (LeetCode) are copyrighted by Owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.Source: LeetCode (LeetCode) Link: https://leetcode-cn.com/problems/reverse-string-ii
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.