2023年7月28日 星期五

7/28 每日一題(反轉字元 )

 Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer 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 leave the other as original.

 

Example 1:

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

Example 2:

Input: s = "abcd", k = 2
Output: "bacd"

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of only lowercase English letters.
  • 1 <= k <= 104



class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        if len(s)==1:
            return s
        lis_s=list(s)
        res=[]
        n=0
        while (n+1)*k <= len(s):
            slice_s=lis_s[(n*k):(n+1)*k]  
        #0-2(n=0),2-4(n=1),n偶數時需要反轉,反之不用
            if n % 2 ==0:
                slice_s=slice_s[::-1]
            res += slice_s
            n+=1
        if len(s) != len(res):
            l=len(s)-len(res)
            if n % 2 ==0:
                res += lis_s[-1:-l-1:-1]  #n偶數時需要反轉,反之不用
            else:
                res += lis_s[-l::]
        return  ''.join(res)


       


























標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁