刷题Day(7) | 代码随想录

96 阅读1分钟

本系列文章是我刷代码随想录过程中的笔记。代码地址:leetcode

今天是我刷“代码随想录”的第七天

今日内容

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

leetcode 344. 反转字符串

这道题可以直接使用库函数。

class Solution:
    def reverseString(self, s: List[str]) -> None:
        s.reverse()

但是这样做就没有了意义。这道题考察的是对于reverse()函数的理解,需要我们自己实现。这里我们采用双指针法进行实现。定义头尾指针,然后交换,最后分别步进1。

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

leetcode 541. 反转字符串II

这道题的话,难在如何处理边界值。

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        def reverse_substring(text):
            left, right = 0, len(text) - 1
            while left < right:
                text[left], text[right] = text[right], text[left]
                left += 1
                right -= 1
            return text
        res = list(s)
        for cur in range(0, len(s), 2 * k):
            res[cur: cur + k] = reverse_substring(res[cur: cur + k])
        return ''.join(res)

leetcode 剑指 Offer 05. 替换空格

简单题。定义一个新字符串,碰到空格就转化为%20,其余字符直接照抄。返回新字符串就好。

class Solution:
    def replaceSpace(self, s: str) -> str:
        newS = ""
        for i in s:
            if i == " ":
                newS += "%20"
            else:
                newS += i
        return newS

leetcode 151. 反转字符串中的单词

这道题的难点在于空格的处理。在拆分字符串之前,需要先处理前后空格。再拆分过程中,也有可能产生空格,也需要处理。最后返回的字符串也会产生不必要的空格。

class Solution:
    def reverseWords(self, s: str) -> str:
        # 去除前空格
        s = self.strip(s)
        l = []
        item = ""
        for i in s:
            if i == " ":
                if item == "": continue
                l.append(item)
                item = ""
            else:
                item += i
        l.append(item)
        left = 0
        right = len(l) - 1
        while left <= right:
            l[left], l[right] = l[right], l[left]
            left += 1
            right -= 1
        newStr = ""
        for i in l:
            newStr += i + " "
        return self.strip(newStr)

    def strip(self, s):
        i = 0
        while s[i] == " ": i += 1
        s = s[i:]
        i = len(s) - 1
        while s[i] == " ": i -= 1
        s = s[:i + 1]
        return s

leetcode 剑指 Offer 58 - II. 左旋转字符串

典型做法

class Solution:
    def reverseLeftWords(self, s: str, n: int) -> str:
        tmp = ""
        for i in range(n):
            tmp += s[i]
        return s[n:] + tmp

也可以python一行流

return s[n:] + s[:n]

总结

今天的题比较简单,但是当限制空间使用的时候还需要一些比较巧妙的处理方式。