class Solution:
def reverseStr(self, s: str, k: int) -> str:
remain = len(s)
res = list(s)
def swap(front:int,rear:int) -> str:
while front < rear:
res[front], res[rear] = res[rear], res[front]
front += 1
rear -= 1
return ''.join(res)
if k > remain:
ans = swap(len(s) - remain,len(s) - 1)
return ans
while k <= remain:
ans = swap(len(s) - remain, len(s) - remain + k - 1)
remain -= 2*k
if remain<k:
ans = swap(len(s) - remain,len(s) - 1)
return ans
elif remain<2*k and remain>k:
ans = swap(len(s) - remain,len(s) - 1)
return ans
return ans
class Solution:
def reverseStr(self, s: str, k: int) -> str:
remain = len(s)
res = list(s)
def swap(res:list[str]) -> list[str]:
front, rear = 0, len(res) - 1
while front < rear:
res[front], res[rear] = res[rear], res[front]
front += 1
rear -= 1
return res
for i in range(0, len(res), 2*k): #i每次跳2k,找到下一个待swap的字符串
res[i: i + k] = swap(res[i: i + k])
#若[i: i + k] out of index 则会截取到字符串最后一个字母
return ''.join(res)