作业(十三)——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]
思路
题目是将字符串每2k个字符反转前k个
我的做法是while循环每次减去k个字符,设置一个反转标志,判断这段是否反转。
代码
class Solution:
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
m=[]
f=1
while len(s)>k:
if f==1:
m.append(s[:k][::-1])
else:
m.append(s[:k])
f=-f
s=s[k:]
if f==1:
m.append(s[:][::-1])
else:
m.append(s[:])
return ''.join(m)
结果