LeetCode刷题记录2020-10-08之动态规划入门!!!线性DP(三)

题目一、打卡
344. 反转字符串

def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        # 双指针、元素交换
        i = 0
        j = len(s) - 1
        while i < j:
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1
        return s

题目二、

345. 反转字符串中的元音字母(打卡题类似题目)

def reverseVowels(self, s: str) -> str:
        # 用字典存储特判值比列表遍历快
        d = {'a': 1, 'e': 1, 'i': 1, 'o':1, 'u':1,'A': 1, 'E': 1, 'I': 1, 'O':1, 'U':1}
        i = 0
        j = len(s) - 1
        sList = list(s)
        while i < j:
            while not d.get(sList[i]) and i < j:
                i += 1
            while not d.get(sList[j]) and i < j:
                j -= 1
            if i < j:
                sList[i], sList[j] = sList[j], sList[i]
            i += 1
            j -= 1
        return ''.join(sList)

题目三、

416. 分割等和子集

def canPartition(self, nums: List[int]) -> bool:
        # 0-1背包问题的变种
        lenth = len(nums)
        total = sum(nums)
        if total % 2 != 0:
            return False
        total = total // 2
        dp = [True] + [False for _ in range(total)]
        for i in nums:
            for j in range(total, i-1, -1):
                dp[j] |= dp[j-i]
        return dp[-1]

# 模板,上面的效率更快
def canPartition(self, nums: List[int]) -> bool:
        # 0-1背包问题的变种
        lenth = len(nums)
        total = sum(nums)
        if total % 2 != 0:
            return False
        total = total // 2
        dp = [0 for _ in range(total+1)]
        for i in nums:
            for j in range(total, i-1, -1):
                dp[j] = max(dp[j], dp[j-i] + i)
        return dp[total] == total

题目四、

978. 最长湍流子数组

def maxTurbulenceSize(self, A: List[int]) -> int:
        # [0,1,1,0,1,0,1,1,0,0]
        lenth = len(A)
        if lenth == 0:
            return 0
        if lenth == 1 or min(A) == max(A):
            return 1
        dp = [1 for _ in range(lenth)]
        res = 1
        tmp_len = 1
        for i in range(1, lenth-1):
            if A[i-1] < A[i] > A[i+1] or A[i-1] > A[i] < A[i+1]:
                dp[i] = dp[i-1] + 1
        return max(dp) + 1
原文地址:https://www.cnblogs.com/854594834-YT/p/13783332.html