leetcode541. Reverse string II (strings are always killed by py)

Given a string s and an integer k, you need to reverse the first k characters every 2k characters from the beginning of the string.

If the remaining characters are less than k, then all the remaining characters are reversed.
If the remaining characters are less than 2k but greater than or equal to k, the first k characters are reversed and the remaining characters remain as they are.
 

Example:

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

prompt:

The string contains only lowercase English letters.
The length of the given string and k are in the range [1, 10000].

Idea: In layman's terms, k reversals every k, and all reversals when there are not enough k at the end;

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        left, mid, right = 0, k, 2 * k                  # 初始化左中右指针
        res = ''                                        # 初始化结果字符串
        while len(res) < len(s):                        # 满足条件时执行
            res += s[left:mid][::-1] + s[mid:right]     # 把当前单元的结果添加到结果字符串
            left, mid, right = left + 2 * k, mid + 2 * k, right + 2 * k                          
        return res                                      # 返回结果

 

Guess you like

Origin blog.csdn.net/hebtu666/article/details/114397405