[541] LeetCode reverse text II

Title: Given a string and an integer k, you need to first k characters of each 2k characters from the beginning of the string is reversed. If the remaining less than k characters, then all remaining completely inverted. If there is less than but greater than or equal to 2k k characters, the characters before the reverse k, and the intact remaining characters.

Example:

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

The string contains only lowercase letters.
Given string length and k in the range [1, 10000].

class Solution {
    public String reverseStr(String s, int k) {
        int len = s.length();
        char[] chars = s.toCharArray();
        int index = 0;

        while (index < len) {
            //判断剩余的字符是否够k=2个,不够k  全部翻转, k<len-index<2k 翻转前k
            if (len - index > k) {
                //局部反转,l指向左,r指向右
                for (int l = index, r = index + k - 1; l < r; l++, r--) {
                    char temp = chars[l];
                    chars[l] = chars[r];
                    chars[r] = temp;
                }
                index = index + 2 * k;
            } else {
                for (int l = index, r = len - 1; l < r; l++, r--) {
                    char temp = chars[l];
                    chars[l] = chars[r];
                    chars[r] = temp;
                }
                //置换结束,退出循环
                index = len;
            }
        }
        return new String(chars);
    }
}
Published 55 original articles · won praise 14 · views 20000 +

Guess you like

Origin blog.csdn.net/qq422243639/article/details/103747567