25期代码随想录算法训练营第八天 | 字符串 part 1

目录

  • 344.反转字符串
  • 541. 反转字符串II
  • 剑指Offer 05.替换空格
  • 151.翻转字符串里的单词
  • 剑指Offer58-II.左旋转字符串

344.反转字符串

链接

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

        while l < r:
            s[l], s[r] = s[r], s[l]
            l += 1
            r -= 1

541. 反转字符串II

链接

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        for i in range(0, len(s), 2*k):
            s = s[:i] + s[i:i+k][::-1] + s[i+k:]

        return s

剑指Offer 05.替换空格

链接

class Solution:
    def pathEncryption(self, path: str) -> str:
        res = []
        for i in path:
            if i == '.':
                i = ' '
            res.append(i)
        return ''.join(res)

151.翻转字符串里的单词

链接

class Solution:
    def reverseWords(self, s: str) -> str:
        # split()会自动 分开单词
        # 以空格来分 而且前后会去除多余空格
        words = s.split()

        return " ".join(words[::-1])

剑指Offer58-II.左旋转字符串

链接

class Solution:
    def dynamicPassword(self, password: str, target: int) -> str:
        return password[target:] + password[:target]

你可能感兴趣的:(算法训练营二刷,算法,python,leetcode)