관리 메뉴

솜씨좋은장씨

[leetCode] 541. Reverse String II (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 541. Reverse String II (Python)

솜씨좋은장씨 2020. 6. 22. 21:07
728x90
반응형

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]

Solution

class Solution:
    def reverseStr(self, s, k):

        list_s = list(s)
        for s in range(0, len(s), 2*k):
            list_s[s:s+k] = list_s[s:s+k][::-1]
        return "".join(list_s)

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments