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. python

Example:shell

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

分析

這是一個字符串反轉的問題,只是這裏多了一個步長k的參數。若是前k個參數進行了反轉,則後k個字符串不進行反轉。所以咱們能夠設置一個標誌位flag,若是爲True,則對接下來k個字符串反轉,不然保持原狀。每k步對flag進行一次取反。less

代碼

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個字符是一個子問題:code

for idx in range(0, len(s), 2*k):
    s = s[:idx] + s[idx:idx+k][::-1] + s[idx+k:]
return s
相關文章
相關標籤/搜索