Python simple solution


  • 3
    W
    class Solution(object):
        def reverseStr(self, s, k):
            """
            :type s: str
            :type k: int
            :rtype: str
            """
            news = ''
            n = (len(s) // (2 * k)) * 2 * k
            for i in range(0, n, 2 * k):
                news += s[i:i + k][::-1]
                news += s[i + k:i + 2 * k]
            if len(s) - n < k:
                news += s[n:][::-1]
            else:
                news += s[n:n + k][::-1]
                news += s[n + k:]
            return news
    

  • 0
    A

    @woqishi n = (len(s) // (2 * k)) * 2 * k can you provide your intuition about this


  • 0

    Same idea but a one liner (a little bit ugly):

        def reverseStr(self, s, k):
            return "".join(s[i*k: i*k+k][::(i&1)*2-1] for i in xrange(len(s)/k + 1))
    

Log in to reply
 

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