給定一個字符串和一個整數 k,你需要對從字符串開頭算起的每個 2k 個字符的前k個字符進行反轉。如果剩餘少於 k 個字符,則將剩餘的所有全部反轉。如果有小於 2k 但大於或等於 k 個字符,則反轉前 k 個字符,並將剩餘的字符保持原樣。
示例:
輸入: s = "abcdefg", k = 2
輸出: "bacdfeg"
思路:切片 + 棧
切片是根據題目需求,將偶數位置的切片進行反轉,反轉用到了棧先進後出的特點,將每個小字符串按照字符依次放入棧中之後再依次取出
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
slice_list = list()
res_list = list()
index = 0
while index < len(s):
slice_list.append(s[index:index+k])
index += k
# 將偶數切片索引的翻轉
for i in range(len(slice_list)):
if i % 2 == 1:
res_list.append(slice_list[i])
else:
stack = [j for j in slice_list[i]] # 利用棧來翻轉
reverse = ""
for k in range(len(stack)):
reverse += stack.pop()
res_list.append(reverse)
return ("".join(res_list))