541. Reverse String II

https://leetcode.com/contest/leetcode-weekly-contest-23/problems/reverse-string-ii/

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.

1
2
3
Example:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Restrictions:

  • The string consists of lower English letters only.
  • Length of the given string and k will in the range [1, 10000]

my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
n = len(s)
cur = 0
res = ''
while cur<n:
if cur+2*k<=n:
res+=s[cur:cur+k][::-1]
res+=s[cur+k:cur+2*k]
cur += 2*k
elif cur+k> n:
res+=s[cur:][::-1]
return res
else:
res+=s[cur:cur+k][::-1]
res+=s[cur+k:]
return res
return res
谢谢你,可爱的朋友。