leetcode541. Reverse String II

来源:互联网 发布:苏州java软件开发招聘 编辑:程序博客网 时间:2024/06/03 11:41

541. Reverse String II

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less 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 left the other as original.

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

Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]

解法

i = i + 2 * k
临界点:i + k - 1和arr.length的长度比较。
如果k >= arr.length,则0 ~ arr.length-1全部反转;
如果i+k-1 < arr.length, 则0 ~ i+k-1全部反转;
如果i+k-1 >= arr.length, 则0 ~ arr.length-1全部反转。
综上,每次取min(i + k -1, arr.length-1)作为反转的右侧边界。

public class Solution {    public String reverseStr(String s, int k) {        if (s == null || s.length() == 0) {            return "";        }        char[] arr = s.toCharArray();        int length = arr.length;        for (int i = 0; i < length; i = i + 2 * k) {            int n = Math.min(i + k - 1, length - 1);            reverse(arr, i, n);        }        return new String(arr);    }    public void reverse(char[] s, int left, int right) {        while (left < right) {            char temp = s[left];            s[left] = s[right];            s[right] = temp;            left++;            right--;        }    }}
原创粉丝点击