541. 反转字符串II

双指针法

class Solution {
    public String reverseStr(String s, int k) {
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i += 2 * k) {
            int left = i;
            int right = Math.min(i + k - 1, ch.length - 1);
            while (left < right) {
                char temp = ch[left];
                ch[left] = ch[right];
                ch[right] = temp;
                left++;
                right--;
            }
        }
        return new String(ch);
    }
}

关键

取最小值 Math.min()

你可能感兴趣的:(java,算法,数据结构)