leetcode contest:week 150 Python解法汇总(二)

前文

  继上周的week 149,接着分享week 150的题目,话不多说,让我们愉快的开始吧。

1160. Find Words That Can Be Formed by Characters
题目大意:求给定集合里的数是否都在chars里面,每个数只能用一次

You are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: 
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2:


Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: 
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

解法:暴力循环,简单粗暴:


class Solution:
    """
    题意是求给定集合里的数是否都在chars里面,每个数只能用一次
    解法:即暴力循环,每次判断集合里数是否存在,存在就删除,不存在就说明不符合,直到遍历完
    """
    def countCharacters(self, words, chars: str) -> int:
        res = ""
        for word in words:
            flag = 0
            strs = chars
            for alp in word:
                if alp not in strs:
                    flag = 1
                    break
                else:
                    strs = strs.replace(alp,'',1)
            if flag == 0:res += word
        return len(res)
1161. Maximum Level Sum of a Binary Tree
题目大意:树的最大层级和,返回对应的层级

Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level X such that the sum of all the values of nodes at level X is maximal.

Example 1:


Input: [1,7,0,7,-8,null,null]
Output: 2
Explanation: 
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.

Note:

The number of nodes in the given tree is between 1 and 10^4.
-10^5 <= node.val <= 10^5

解法:BFS层级遍历,计数+求和比较

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


class Solution:
    """
    题意是求树的最大层级和,返回对应的层级
    解法和102题求tree的层级遍历一致,不过需要增加每层的计数、求和比较
    通过BFS将每层的层级和求出,然后指定最大和变量max,最后返回最大和所对应的层级index即可
    """
    def maxLevelSum(self, root: TreeNode) -> int:
        from collections import deque
        if not root: return []
        queue, res, ans, index = deque([root]), 0, 0, 1

        while queue:
            cur_level, size = [], len(queue)
            for i in range(size):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                cur_level.append(node.val)
            sum1 = sum(cur_level)
            print(sum1)
            if sum1 > res:
                res = sum1
                ans = index
            index += 1

        return ans


1162. As Far from Land as Possible
题目大意:求一个方形矩阵中,最远距离的1和0是多远

Given an N x N grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized and return the distance.

The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.

If no land or water exists in the grid, return -1.

在这里插入图片描述

Input: [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation: 
The cell (1, 1) is as far as possible from all the land with distance 2.

在这里插入图片描述

Input: [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation: 
The cell (2, 2) is as far as possible from all the land with distance 4.

Note:

1 <= grid.length == grid[0].length <= 100
grid[i][j] is 0 or 1

解法:来自讨论区大神的解法,BFS

class Solution:
    """
    题意是求一个方形矩阵中,1假设为陆地,0假设为水,最远距离的陆地和水是多远,默认左上角为(0.0)
    解法通过BFS,即先找出所有1的点,然后在1的上下左右找到0的点为一层,把该点设为1,再围绕这个1去找对应的
    外面一层0的店,直到找完全部
    """
    def maxDistance(self, grid: List[List[int]]) -> int:
        from collections import deque
        m,n = len(grid), len(grid[0])
        q = deque([(i,j) for i in range(m) for j in range(n) if grid[i][j] == 1])
        if len(q) == m * n or len(q) == 0: return -1
        level = 0
        while q:
            size = len(q)
            for _ in range(size):
                i,j = q.popleft()
                for x,y in [(1,0), (-1, 0), (0, 1), (0, -1)]:
                    xi, yj = x+i, y+j
                    if 0 <= xi < m and 0 <= yj < n and grid[xi][yj] == 0:
                        q.append((xi, yj))
                        grid[xi][yj] = 1
            level += 1
        return level-1
1163. Last Substring in Lexicographical Order
题目大意:求字符串里的最大字典序

User Accepted: 750
User Tried: 1610
Total Accepted: 800
Total Submissions: 4468
Difficulty: Hard
Given a string s, return the last substring of s in lexicographical order.

Example 1:

Input: "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".

Example 2:

Input: "leetcode"
Output: "tcode"

Note:

1 <= s.length <= 4 * 10^5
s contains only lowercase English letters.

解法:参照讨论区大神解法


class Solution:
    def lastSubstring(self, s: str) -> str:
        if len(set(s)) == 1: return s
        idx = len(s) - 1
        for i in range(len(s)-2, -1, -1):
            k = 0
            while idx+k < len(s):
                cur, stored = ord(s[i+k]), ord(s[idx+k])
                if cur > stored:
                    idx = i
                    break
                elif cur < stored:
                    break
                k += 1
            if idx+k == len(s):
                idx = i
        return s[idx:]

总结

  本次分享到此,谢谢观看~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值