地里新农-请到考试中心学习规则
- 积分
- 3
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2022-8-11
- 最后登录
- 1970-1-1
|
本帖最后由 ahadv 于 2022-10-11 02:07 编辑
如果觉得有用, 就加个米吧 ..
第一题- def removeParenthese(s):
- arr = ['+'] + [*s]
- stack = []
- op = None
- pre_op = {} # operator before the (
- toggle = [0] * len(arr) # flip the operator
- for i, c in enumerate(arr):
- if c == '-' or c == '+':
- op = c
- elif c == '(':
- stack.append((c, i))
- pre_op[i] = op
- elif c == ')':
- (_, p) = stack.pop()
- # e.g. -(a+b-c) the pre_op is '-', update all oper inside for the parenthese
- if pre_op[p] == '-':
- for k in range(p, i):
- if arr[k] == '-' or arr[k] == '+':
- toggle[k] += 1
- opers = ['+', '-']
- res = []
- for i, c in enumerate(arr):
- if c == '+' or c == '-':
- newop = opers[(opers.index(c) + toggle[i]) % 2]
- res.append(newop)
- elif c.isalpha():
- res.append(c)
-
- return ''.join(res[1:])
-
- print(removeParenthese('(a-(b+c-(f+g))+d)'))
- print(removeParenthese('(a-(b+c)+d)'))
- print(removeParenthese('((((b-c))))'))
复制代码 第二题- import collections
- def dfs(node, visited, adj, coins):
- if visited[node]: return 0
- visited[node] = True
- amount = coins[node]
- for nei in adj[node]:
- amount += dfs(nei, visited, adj, coins)
- return amount
-
- def winCoin(A):
- m = len(A)
- n = len(A[0])
- coins = [0] * n # each column total coin
- adj = collections.defaultdict(set)
- for i in range(m):
- first_col = None
- for j in range(n):
- if A[i][j] == 1:
- coins[j] += 1
- if first_col == None:
- first_col = j
- else:
- adj[first_col].add(j)
- adj[j].add(first_col)
-
- res = 0
- visited = [False] * n
- for i in range(n):
- if not visited[i]:
- amount = dfs(i, visited, adj, coins)
- res = max(res, amount)
- return res
- m = [
- [0,0,1,0,1,0],
- [0,0,1,0,0,0],
- [0,1,0,0,1,0],
- [0,1,0,1,0,0],
- [1,0,0,0,0,1],
- ]
- print(winCoin(m))
复制代码 |
|