leetcode刷题记录811-820 python版

前言

继续leetcode刷题生涯
这里记录的都是笔者觉得有点意思的做法
参考了好几位大佬的题解,感谢各位大佬

811. 子域名访问计数

class Solution:
    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
        if not cpdomains: return []
        res = {}
        for case in cpdomains:
            time, web = case.split()
            for i in range(len(web.split('.'))):
                dm = web.split('.', i)[-1]
                res[dm] = res.get(dm, 0) + int(time)
        return [str(v) + ' ' + k for k, v in res.items()]

812. 最大三角形面积

from itertools import combinations
class Solution:
    def largestTriangleArea(self, points: List[List[int]]) -> float:
        return max(abs((x0-x2)*(y1-y2)-(x1-x2)*(y0-y2)) for (x0,y0),(x1,y1),(x2,y2) in combinations(points,3))/2

813. 最大平均值和的分组

class Solution:
    def largestSumOfAverages(self, A: List[int], K: int) -> float:
        N = len(A)
        dp = [[0]*N for _ in range(K)]
        for j in range(N-K+1):
            dp[0][j] = sum(A[:j+1])/(j+1)
        for i in range(1, K):
            for j in range(i, N-K+i+1):
                for p in range(i-1, j):
                    dp[i][j] = max(dp[i-1][p] + sum(A[p+1:j+1])/(j-p), dp[i][j])
        return dp[-1][-1]

814. 二叉树剪枝

class Solution:
    def pruneTree(self, root: TreeNode) -> TreeNode:
        if not root: return None
        root.left = self.pruneTree(root.left)
        root.right = self.pruneTree(root.right)
        if root.val == 0 and not root.left and not root.right:
            return None
        return root

815. 公交路线

class Solution:
    def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:
        if S == T: return 0
        d = {} #直达
        for i in range(0, len(routes)):
            for j in routes[i]:
                if j in d:
                    d[j].add(i)
                else:
                    d[j] = set({i})
        h = set() #换乘
        for key, value in d.items():
            if len(value) > 1:
                h.add(key)
        visited = set({S})
        queue = [S]
        res = 1
        n = 1
        while len(queue) > 0:
            front = queue.pop(0)
            for bus in d[front]:
                if T in routes[bus]:
                    return res
                for site in routes[bus]:
                    if site in h and site not in visited:
                        queue.append(site)
                        visited.add(site)
            n -= 1
            if n == 0:
                n = len(queue)
                res += 1
        return -1

816. 模糊坐标

import itertools
class Solution:
    def ambiguousCoordinates(self, S: str) -> List[str]:
        def zero(s):
            if len(s) == 1:
                return [s]
            elif s[0] == '0' and s[-1] == '0':
                return None
            elif s[0] == '0':
                return [s[0] + '.' + s[1:]]
            elif s[-1] == '0':
                return [s]
            else:
                return [s[:i]+'.'+s[i:]  for i in range(1,len(s))] + [s]
        S = S[1:-1]
        n = len(S)
        res = []
        for i in range(1,n):
            s1 = zero(S[:i])
            s2 = zero(S[i:])
            if s1 and s2:
                for m, n in itertools.product(s1, s2):
                    res.append('(' + ', '.join([m,n]) + ')')
        return res
# 笛卡尔积
class Solution:
    def ambiguousCoordinates(self, S: str) -> List[str]:
        def f(s):
            if not s or len(s) > 1 and s[0] == s[-1] == '0':
                return []
            if len(s) > 1:
                if s[0] == '0':
                    return [s[0] + '.' + s[1: ]]
                if s[-1] == '0':
                    return [s]
            return [s] + [s[: i] + '.' + s[i: ] for i in range(1, len(s))]
        S = S[1: -1]
        return ['(%s, %s)'%(x, y) for i in range(1, len(S)) for x, y in itertools.product(f(S[: i]), f(S[i: ]))]

817. 链表组件

class Solution:
    def numComponents(self, head: ListNode, G: List[int]) -> int:
        res = 0
        tmp = flag = False
        G_set = set(G)
        while head:
            flag = head.val in G_set
            if (tmp ^ flag) & flag:
                res += 1
            tmp = flag
            head = head.next
        return res

818. 赛车

class Solution:
    def racecar(self, target: int) -> int:
        dp = [float('inf')] * (target + 1)
        for i in range(1, target + 1):
            k = 1  # A的次数
            pos = 1
            while pos < i:  # pos < target
                q = 0  # R过一次后A的次数
                while ((1 << q) - 1) < pos:
                    dp[i] = min(dp[i], k + 1 + q + 1 + dp[i - (pos - ((1 << q) - 1))])
                    q += 1
                k += 1
                pos = (1 << k) - 1

            if i == pos:  # pos == target
                dp[i] = k
            else:  # pos > target
                dp[i] = min(dp[i], k + 1 + dp[pos - i])

        return dp[target]

819. 最常见的单词

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        import re
        import collections
        l = re.findall('[a-zA-Z]+',paragraph)
        l = [i.lower() for i in l]  #忽略大小写
        count = collections.Counter(l)  #建计数表
        for i in count:
            if i in banned:
                count[i]=0            #ban词置0
        res = count.most_common(1)
        # res = list(count.items())
        # res.sort(key=lambda x:x[1])
        return res[0][0]

820. 单词的压缩编码

class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        word = set(words)
        sum = 0
        for i in words:
            for j in range(1, len(i)):
                word.discard(i[j:])
        for k in word:
            sum += len(k)+1
        return sum

你可能感兴趣的:(leetcode,leetcode,python)