LeetCode541. Reverse String II -- 按步长反转字符串

描述

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值