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. python
Example:shell
Input: s = "abcdefg", k = 2 Output: "bacdfeg"
这是一个字符串反转的问题,只是这里多了一个步长k的参数。若是前k个参数进行了反转,则后k个字符串不进行反转。所以咱们能够设置一个标志位flag
,若是为True
,则对接下来k个字符串反转,不然保持原状。每k步对flag
进行一次取反。less
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
个字符是一个子问题:code
for idx in range(0, len(s), 2*k): s = s[:idx] + s[idx:idx+k][::-1] + s[idx+k:] return s