Skip to content

541. Reverse String II

https://leetcode.com/problems/reverse-string-ii/

js
/**
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
var reverseStr = function(s, k) {
  let result = ''
  let i = 0

  while (i < s.length) {
    result += s.slice(i, i + k).split('').reverse().join('')
    result += s.slice(i + k, i + 2 * k)
    i += 2 * k
  }

  return result
}
py
class Solution:

    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        result = ''
        i = 0

        while i < len(s):
            result += s[i:i + k][::-1]
            result += s[i + k:i + 2 * k]
            i += 2 * k

        return result