leetcode541 反转字符串 II

按题意操作即可。

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        def _rev(s):
            pass
        
        s=[c for c in s]
        result=[]
        while len(s)>0:
            if len(s)>=2*k:
                a=s[0:k]
                a.reverse()
                result.extend(a)
                result.extend(s[k:2*k])
                s=s[2*k:]
            elif len(s)

或者:

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        a = []
        for i in range(k, len(s)+k, 2 * k):
            a.extend((s[i - k:i][::-1], s[i:i + k]))
        return ''.join(a)

 

你可能感兴趣的:(算法面试题)