Leetcode周赛150,拼写单词,最大层内元素和,地图分析,按字典序排在最后的子串

本文提供了LeetCode周赛150的三道题目的详细解答,包括字符计数、树的最大层级和与网格中最远海洋的距离。通过算法和数据结构的巧妙运用,展示了如何高效解决这些挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode-cn.com/contest/weekly-contest-150

class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        data = [collections.Counter(i) for i in words]#分别统计每个单词中每个字母的数量
        chs = collections.Counter(chars)#分别统计给定字符串中的字母数量
        res = 0
        for i, k in enumerate(data):#遍历每个单词中的字母数量
            for j, v in k.items():
                if chs[j] < v:#如果字母数量不够的话
                    break
            else:
                res += len(words[i])#遍历完之后加上该字母的长度
        return res

 

思路是使用树的层遍历,利用队列实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxLevelSum(self, root: TreeNode) -> int:
        q, res, ret, level = [root], 0, 0, 0
        while any(q):
            cur, tmp = [], 0
            for _ in range(len(q)):#队列层序遍历树
                node = q.pop(0)
                tmp += node.val
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            level += 1
            if tmp > res:#每遍历完一层,时刻准备替换为最大值
                res = tmp
                ret = level
        return ret
                

思路是多源BFS,从队列中取出一个陆地,向四周扩散一圈,并将扩散的一圈标记为2,3,4,5,6...并将扩散到的区域放入到队列中,这是传统的BFS,在这里只不过是从多点同时开始开始BFS,直到没有空闲的点之后,就找到了最远的海洋


class Solution:
    def maxDistance(self, grid: List[List[int]]) -> int:
        r, c = len(grid), len(grid[0])
        rot = list()
        for i in range(r):
            for j in range(c):
                if grid[i][j] == 1:
                    rot.append((i, j, 0))#找到所有的陆地放入队列中
        
        d = [(0,1), (0,-1), (1,0), (-1,0)]#四个方向
        res = 0
        while rot:
            i, j, res = rot.pop(0)
            for xd, yd in d:
                x = i + xd
                y = j + yd
                if 0 <= x < r and 0 <= y < c and grid[x][y] == 0:#边界以及未曾遍历判断
                    grid[x][y] = grid[xd][yd] + 1
                    rot.append((x, y, res+1))
        
        return res if res != 0 else -1


 

按照字典序的话,最大的必定是从某点开始到字符串尾部的某个子串,因为leetcode肯定比leetcod大啊,所以依次比较,某个点到字符串尾部的子串就行

class Solution:
    def lastSubstring(self, s: str) -> str:
        mx = ""
        for i in range(len(s)):
            mx = max(mx, s[i:])

        return mx

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值