按题意操作即可。
class Solution:
def reverseStr(self, s: str, k: int) -> str:
def _rev(s):
pass
s=[c for c in s]
result=[]
while len(s)>0:
if len(s)>=2*k:
a=s[0:k]
a.reverse()
result.extend(a)
result.extend(s[k:2*k])
s=s[2*k:]
elif len(s)<k:
a=s[:]
a.reverse()
result.extend(a)
s=[]
elif k<=len(s)<2*k:
a=s[0:k]
a.reverse()
result.extend(a)
result.extend(s[k:])
s=[]
return "".join(result)
或者:
class Solution:
def reverseStr(self, s: str, k: int) -> str:
a = []
for i in range(k, len(s)+k, 2 * k):
a.extend((s[i - k:i][::-1], s[i:i + k]))
return ''.join(a)