Formatted question description: https://leetcode.ca/all/541.html

# 541. Reverse String II

Easy

## Description

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 = 2

Output: “bacdfeg”

Restrictions:

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

## Solution

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;
l++;
r--;
}
}
return new String(a);
}
}
}

• Todo

• class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
cnt = 0
isFirst = True
a = ""
b = ""
ans = []
for c in s:
if isFirst:
a = c + a
else:
b += c
cnt += 1
if cnt == k:
if isFirst:
ans.append(a)
a = ""
else:
ans.append(b)
b = ""
isFirst = not isFirst
cnt = 0
return "".join(ans) + a + b