0541. Reverse String I I

541. Reverse String II #

Problem #

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]

Problem Summary #

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 fewer than k characters left, reverse all the remaining characters. If there are fewer than 2k but greater than or equal to k characters, reverse the first k characters and leave the remaining characters as they are.

Requirements:

  • The string contains only lowercase English letters.
  • The length of the given string and k are in the range [1, 10000].

Solution Ideas #

  • The requirement is to reverse the string according to certain rules: for every substring of length 2 * K, reverse the first K characters, while keeping the latter K characters unchanged; for the substring at the end that is shorter than 2 * K, if its length is greater than K, then reverse the first K characters and keep the rest unchanged. If its length is less than K, then reverse this entire substring of length less than K.
  • This is an easy problem; just reverse the string according to the problem statement.

Code #


package leetcode

func reverseStr(s string, k int) string {
	if k > len(s) {
		k = len(s)
	}
	for i := 0; i < len(s); i = i + 2*k {
		if len(s)-i >= k {
			ss := revers(s[i : i+k])
			s = s[:i] + ss + s[i+k:]
		} else {
			ss := revers(s[i:])
			s = s[:i] + ss
		}
	}
	return s
}

func revers(s string) string {
	bytes := []byte(s)
	i, j := 0, len(bytes)-1
	for i < j {
		bytes[i], bytes[j] = bytes[j], bytes[i]
		i++
		j--
	}
	return string(bytes)
}



Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文