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:]

總結

  本次分享到此,謝謝觀看~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章