LeetCode 第 272 场周赛总结

266 阅读1分钟

5956. 找出数组中的第一个回文字符串

我的代码:执行用时: 60 ms 内存消耗: 15.2 MB

class Solution:
    def findStr(self, s):
        for i in range(len(s)//2):
            if s[i] != s[-i-1]:
                return False
        return True
    def firstPalindrome(self, words: List[str]) -> str:
        for s in words:
            if self.findStr(s):
                return s
        return ''

大佬的代码:执行用时: 28 ms 内存消耗: 15 MB

class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        for c in words:
            if c==c[::-1]:
                return c
        return ""

5957. 向字符串添加空格

我的代码:执行用时: 236 ms 内存消耗: 39.9 MB

class Solution:
    def addSpaces(self, s: str, spaces: List[int]) -> str:
        l = [''] * (len(spaces) + len(s))
        pre = -1
        for i, num in enumerate(spaces):
            l[num + i]=" "
            for j in range(pre+i, num+i):
                l[j] = s[j-i]
            pre = num
        for j in range(pre+len(spaces), len(l)):
            l[j] = s[j-len(spaces)]
        return "".join(l)

大佬的代码:执行用时: 208 ms 内存消耗: 37 MB

class Solution:
    def addSpaces(self, s: str, spaces: List[int]) -> str:
        spaces.sort()
        ans = []
        for i in range(len(s)-1,-1,-1):
            ans.append(s[i])
            if spaces and spaces[-1]==i:
                ans.append(" ")
                spaces.pop()
        ans=ans[::-1]
        return "".join(ans)

5958. 股票平滑下跌阶段的数目

我的代码:执行用时: 152 ms 内存消耗: 24.9 MB

class Solution:
    def getDescentPeriods(self, prices: List[int]) -> int:
        n = len(prices)
        dp = [1] * n
        for i in range(1, n):
            if prices[i] + 1 == prices[i-1]:
                dp[i] = dp[i-1] + 1
        return sum(dp)

5959. 使数组 K 递增的最少操作次数

官方题解代码:执行用时: 244 ms 内存消耗: 24.8 MB

class Solution:
    def kIncreasing(self, arr: List[int], k: int) -> int:
        n = len(arr)
        ans = 0
        for i in range(k):
            f = list()
            j, length = i, 0
            while j < n:
                length += 1
                it = bisect_right(f, arr[j])
                if it == len(f):
                    f.append(arr[j])
                else:
                    f[it] = arr[j]
                j += k
            ans += length - len(f)
        return ans