# coding:utf-8 """ Name : NO541.py Author : qlb Contect : 17801044486@163.com Time : 2021/2/7 9:28 Desc: 翻转字符串2 """ #解题思路 # 把遍历的步长改为 2*k 即可 将 i:i + k 这段字符串进行翻转 class Solution: def reverseStr(self, s: str, k: int) -> str: s = list(s) for i in range(0, len(s), 2 * k): s[i:i + k] = self.myReverse(s[i:i + k]) return ''.join(s) def myReverse(self, s): i = 0 j = len(s) - 1 while i < j: tmp = s[j] s[j] = s[i] s[i] = tmp i += 1 j -= 1 return s