leetcode#541. 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"

Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]

代码一

题目很简单,答案也很快的写出来了,如下:

class Solution(object):
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        temp = ans = ""
        flag = -1
        for index, i in enumerate(s):
            if index % k == 0:
                ans += temp
                temp = ""
                flag = -flag
            if flag == 1:
                temp = i + temp
            else:
                ans += i
        if temp != "":
            ans += temp
        return ans

提交后发现用时100多毫秒,排名后10%,虽然这是O(n)的算法,但是仔细想了下,的确有更简单的实现方式。

代码二

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

嗯,这下好多了,39ms,排名领先82%的人。这里是利用了python自身的reverse函数以及切片函数,代码简洁的同时还提高了效率。

总结

由于我是从C开始学的,所以总是惯性思维写出代码一那种代码。现在换成python后,得需要转变思维了,一些常用的操作,首先应该想想python是不是自身已经实现了。不得不说,这样的代码写起来更舒服一些~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值