天天看點

力扣(leetcode) 541. 反轉字元串 II

題目在這:​​https://leetcode-cn.com/problems/reverse-string-ii/​​

思路分析:

這道題是之前翻轉字元串的加強版。

每隔 2N個字元,翻轉前N個字元。

可以直接使用帶2N步長的循環就行了,每經過2N個字元翻轉一次,每次翻轉千N次字元。

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        s_list = list(s)
        for i in range(0,len(s_list),2 * k):

            s_list[i:i+k] = s_list[i:i+k][::-1]

        return "".join(s_list)