本文主要是介绍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 = -1for index, i in enumerate(s):if index % k == 0:ans += temptemp = ""flag = -flagif flag == 1:temp = i + tempelse:ans += iif temp != "":ans += tempreturn ans
提交后发现用时100多毫秒,排名后10%,虽然这是O(n)的算法,但是仔细想了下,的确有更简单的实现方式。
代码二
class Solution(object):def reverseStr(self, s, k):""":type s: str:type k: int:rtype: str"""ans = ""flag = 1for i in range(0, len(s), k):temp = ""temp = s[i: i + k]if flag == 1:temp = temp[:: -1]flag = -flagans += tempreturn ans
嗯,这下好多了,39ms,排名领先82%的人。这里是利用了python自身的reverse函数以及切片函数,代码简洁的同时还提高了效率。
总结
由于我是从C开始学的,所以总是惯性思维写出代码一那种代码。现在换成python后,得需要转变思维了,一些常用的操作,首先应该想想python是不是自身已经实现了。不得不说,这样的代码写起来更舒服一些~
这篇关于leetcode#541. Reverse String II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!