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