leetcode刷題記錄1041-1050 python版

思源湖的魚發表於2020-10-07

前言

繼續leetcode刷題生涯
這裡記錄的都是筆者覺得有點意思的做法
參考了好幾位大佬的題解,感謝各位大佬

1041. 困於環中的機器人

class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
        x=y=0
        dx,dy=0,1
        for c in instructions*4:
            if c=='G':
                x+=dx
                y+=dy
            elif c=='L':
                dx,dy = -dy,dx # cos(pi/2+theta),sin(pi/2+theta)
            else:
                dx,dy = dy,-dx
        return x==y==0

1042. 不鄰接植花

class Solution:
    def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]:
        if not paths: return [1] * N
        g = [[]for _ in range(N)] # g[i]表示第i個節點相鄰的所有的節點序號
        res = [0 for _ in range(N)]
        for x, y in paths:
            g[x-1].append(y-1)
            g[y-1].append(x-1)
        for i in range(N):
            res[i]=({1,2,3,4}-{res[j] for j in g[i]}).pop()
        return res

1043. 分隔陣列以得到最大和

class Solution:
    def maxSumAfterPartitioning(self, A: List[int], K: int) -> int:
        n = len(A)
        dp = [0] * (n+1)
        for i in range(1,n+1):
            j = i - 1
            tmp = -float('inf')
            while i - j <= K and j >= 0:
                tmp = max(tmp,A[j])
                dp[i] = max(dp[i],dp[j] + tmp * (i - j))
                j -= 1
        return dp[n]

1044. 最長重複子串

class Solution:
    def longestDupSubstring(self, S: str) -> str:
        import functools
        A = [ord(c) - ord('a') for c in S]
        mod = 2**63 - 1
        n = len(S)
        def test(l):
            p = pow(26,l,mod)
            cur = functools.reduce(lambda x,y:(x*26+y)%mod,A[:l])
            seed = {cur}
            for index in range(l,n):
                cur =(cur * 26 + A[index] - A[index-l] * p) % mod
                if cur in seed:
                    return index - l + 1
                seed.add(cur)
            return -1
        low,high = 0,n
        res = 0
        while low < high:
            mid = (low + high + 1) // 2
            pos = test(mid)
            if pos != -1:
                low = mid
                res = pos
            else:
                high = mid - 1
        return S[res:res+low]

1046. 最後一塊石頭的重量

class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        while len(stones) > 1:
            stones.sort()
            stones.append(stones.pop() - stones.pop())
        return stones[0]
# 堆
from heapq import heapify, heappush, heappop
class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        for i in range(len(stones)):
            stones[i] = -stones[i];
        heapify(stones)
        while len(stones) > 0:
            y = -heappop(stones)
            if len(stones) == 0:
                return y
            x = -heappop(stones)
            if x != y:
                heappush(stones, x - y)
        return 0

1047. 刪除字串中的所有相鄰重複項

class Solution:
    def removeDuplicates(self, S: str) -> str:
        stack = []
        for i in S:
            if stack:
                if stack[-1] == i:
                    stack.pop()
                else: stack.append(i)
            else: stack.append(i)
        return "".join(stack)

1048. 最長字串鏈

class Solution:
    def longestStrChain(self, words: List[str]) -> int:
        words.sort(key=len)
        hashmap = {}
        res = 1
        for word in words:
            if word not in hashmap:
                hashmap[word] = 1
            for i in range(len(word)):
                newword = word[:i] + word[i+1:]
                if newword in hashmap:
                    hashmap[word] = max(hashmap[word], hashmap[newword]+1)
            res = max(res, hashmap[word])
        return res

1049. 最後一塊石頭的重量 II

# 0-1揹包, dp[i][j]代表選i個石頭的最大重量j, 其中容量為sum/2, 即求最大的j<sum/2
class Solution:
    def lastStoneWeightII(self, stones: List[int]) -> int:
        total, n = sum(stones), len(stones)
        dp = [[0]*(total//2+1) for _ in range(n+1)]
        for i in range(1, n+1):
            for j in range(1, total//2+1):
                if stones[i-1] <= j: # 這個代表選第i個, 然後再去比較選之後的大小
                    dp[i][j] = max(dp[i-1][j], dp[i-1][j-stones[i-1]]+stones[i-1])
                else: 
                    dp[i][j] = dp[i-1][j] # 這個代表不選第i個
        return total-2*dp[-1][-1]

相關文章