Python solution with detailed explanation


  • 0
    G

    Solution

    Reverse String II https://leetcode.com/problems/reverse-string-ii/#/description

    class Solution(object):
        def reverse(self, s, i, j):
            while i < j:
                s[i], s[j] = s[j], s[i]
                i, j = i+1, j-1
            return
        
        def reverseStr(self, s, k):
            """
            :type s: str
            :type k: int
            :rtype: str
            """
            i = 0
            s = [x for x in s]
            while i < len(s):
                if i + k-1 < len(s):
                    self.reverse(s, i, i+k-1)
                else:
                    self.reverse(s, i, len(s)-1)
                i = i + 2*k
            return "".join(s)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.