Formatted question description:

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.


Input: s = “abcdefg”, k = 2

Output: “bacdfeg”


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


For the given integer k, find each group with size 2k and reverse the first k characters in each group. If the last group’s size is less than k, then reverse all the letters in the last group.

Transform the string to an array of characters, and do the reverse in each group. Finally, return a string from the array.

public class Reverse_String_II {

    class Solution {
        public String reverseStr(String s, int k) {

            char[] a = s.toCharArray();

            for (int i = 0; i < a.length - 1; i = i + 2*k) {

                int l = i;
                int r = Math.min(a.length - 1, l + k - 1); // inclusive: start+k-1

                while (l < r) {
                    char tmp = a[l];
                    a[l] = a[r];
                    a[r] = tmp;
            return new String(a);

All Problems

All Solutions