541- reverse text II

541- reverse text II

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:

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

Claim:

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

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/reverse-string-ii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

    // 不借助API,最快
    public String reverseStr(String s, int k) {
        char[] a = s.toCharArray();
        for (int start = 0; start < a.length; start += 2 * k) {
            int i = start;
            int 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);
    }
    public String reverseStr_2(String s, int k) {
        // 全部反转
        StringBuilder reverse = new StringBuilder(s).reverse();

        int len = s.length();
        int loop = len / (2 * k);
        int i = 0;

        StringBuilder res = new StringBuilder();
        while (loop > 0) {
            res.append(reverse, len - k - i, len - i).append(s, k + i, 2 * k + i);
            i += 2 * k;
            loop--;
        }

        int remain = len - i;
        if (remain < k) {
            res.append(reverse, 0, remain);
        } else {
            res.append(reverse, len - k - i, len - i).append(s, k + i, len);
        }
        return res.toString();
    }

Ratio above a hurry: only need to reverse the reversal of part

    public String reverseStr_1(String s, int k) {
        // 遍历,反转,拼接
        int len = s.length();
        int loop = len / (2 * k);
        StringBuilder res = new StringBuilder();
        while (loop > 0) {
            res.append(new StringBuilder(s.substring(0, k)).reverse()).append(s, k, 2 * k);
            s = s.substring(2 * k);
            loop--;
        }

        StringBuilder sb = new StringBuilder(s);
        if (sb.length() < k) {
            res.append(sb.reverse());
        } else {
            res.append(new StringBuilder(s.substring(0, k)).reverse()).append(s.substring(k));
        }
        return res.toString();
    }

Guess you like

Origin www.cnblogs.com/angelica-duhurica/p/12236967.html