描述

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.

Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

分析

这是一个字符串反转的问题,只是这里多了一个步长k的参数。如果前k个参数进行了反转,则后k个字符串不进行反转。因此我们可以设置一个标志位flag,如果为True,则对接下来k个字符串反转,否则保持原状。每k步对flag进行一次取反。

代码

class Solution:
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        flag = False
        temp = ""
        for i in range(0, len(s), k):
            flag = not flag
            stop = i+k
            if stop > len(s):
                stop = len(s)
            if flag:
                temp += s[i:stop][::-1]
            else:
                temp += s[i:stop]
        return temp

优化

看了下beats 100%的代码,以2k为步长,则每次迭代只需将反转之前的、反转的和反转之后的三部分加起来,即每2k个字符是一个子问题:

for idx in range(0, len(s), 2*k):
    s = s[:idx] + s[idx:idx+k][::-1] + s[idx+k:]
return s

lingjiu
38 声望6 粉丝

我也想成为一个有趣的人...