Reverse String II

Problem Id: 541 Difficulty: Easy


Intuition

Solution


class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        lo = 0
        ans = []
        while lo < len(s):
            for i in range(min(lo + k, len(s)) - 1, lo - 1, -1):
                ans.append(s[i])
            for i in range(lo + k, min(lo + 2 * k, len(s))):
                ans.append(s[i])
            lo += 2 * k
        return ''.join(ans)