算法第七天 | 344.反转字符串,541.反转字符串II,54.替换数字,151.翻转字符串里的单词,55.右旋转字符串

49 阅读1分钟

344.反转字符串

344.反转字符串

文章讲解

视频讲解

非常基本的题不做过多赘述。

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        left, right = 0, len(s) - 1

        while left < right:
            s[left], s[right] = s[right], s[left]
            
            left += 1
            right -= 1

541. 反转字符串II

文章讲解

视频讲解

重点:理解p + k的范围

class Solution:
    def reverseStr(self, s: str, k: int) -> str:

        p = 0

        while p < len(s):
            p2 = p + k

            s = s[:p] + s[p:p2][::-1] + s[p2:]

            p += 2 * k
        
        return s

151.翻转字符串里的单词

文章讲解

视频讲解

class Solution:
    def reverseWords(self, s: str) -> str:
        
        words = s.split()

        left, right = 0, len(words) - 1

        while left < right:
            words[left], words[right] = words[right], words[left]

            left += 1
            right -= 1

        return ' '.join(words)