Python3 reverse text

Title:
Given a string and an integer k, you need to first k characters of each 2k characters from the beginning of the string is reversed. If the remaining less than k characters, then all remaining completely inverted. If there is less than but greater than or equal to 2k k characters, the characters before the reverse k, and the intact remaining characters.

Example:

输入: s = "abcdefg", k = 2
输出: "bacdfeg"

Problem solving:

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        arr = list(s)
        n = len(s)
        temp = None  #用作交换数据中转站
        for i in range(0, n, 2*k): #i是要反转的字串开始索引
            length = min(n - i, k)  #要反转的字串长度
            j = i + length - 1 #要反转的字串最后索引
            # 执行翻转
            for m in range(i, i + int(length/2)): 
                temp = arr[m]
                arr[m] = arr[i + j - m]
                arr[i + j - m] = temp
        return ''.join(arr)
Published 24 original articles · won praise 0 · Views 420

Guess you like

Origin blog.csdn.net/qq_18138105/article/details/105164517