字符串--反转字符串II

56 阅读1分钟

题意: 给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。
如果剩余字符少于 k 个,则将剩余字符全部反转。
如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。

示例:
输入: s = "abcdefg", k = 2
输出: "bacdfeg"

代码:

public class ReverseStringII {
    public static String reverseStringII(String s, int k) {
        char[] result = s.toCharArray();
        for (int i = 0; i < result.length; i += 2 * k) {
            if (i + k <= s.length()) {
                reverse(result, i, i + k - 1);
            } else {
                reverse(result, i, s.length() - 1);
            }
        }
        return new String(result);
    }

    public static void reverse(char[] result, int i, int j) {
        while (i < j) {
            result[i] = (char) (result[i] ^ result[j]);
            result[j] = (char) (result[i] ^ result[j]);
            result[i] = (char) (result[i] ^ result[j]);
            i++;
            j--;
        }
    }

    public static void main(String[] args) {
        String s = "abcdefg";
        int k = 2;
        System.out.println(reverseStringII(s, k));
    }
}