记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
目录
10/5 856. 括号的分数
栈保存左括号值为0
如果有右括号则取出最后一个值 如果为0说明为空括号 +1 不为0则双倍
加入前一个值中
python
def scoreOfParentheses(s):
"""
:type s: str
:rtype: int
"""
stack = [0]
for c in s:
if c=="(":
stack.append(0)
else:
v = stack.pop()
stack[-1]+=max(2*v,1)
return stack[-1]
10/6 921. 使括号有效的最少添加
左括号必须搭配一个右括号
记录当前左括号数量left 遇到一个右括号 left-1
如果缺少左括号必须添加ans+1
最后如果left>0说明缺少右括号 ans+left
python
def minAddToMakeValid(s):
"""
:type s: str
:rtype: int
"""
ans,left=0,0
for c in s:
if c=="(":
left+=1
elif left>0:
left-=1
else:
ans+=1
return ans+left
10/7 301. 删除无效的括号
先扫一遍,算出最少要删几个左括号、几个右括号:多出来的右括号立刻记一笔,扫完还剩的左括号也要删。
然后从左到右决定每个括号删还是留,字母必须留下。删的数量不能超过刚才算出的最少值,留下的过程中右括号不能比左括号多。
全部处理完且该删的都删掉了,就得到一种答案,用集合去重。
python
def removeInvalidParentheses(s):
"""
:type s: str
:rtype: List[str]
"""
l = r = 0
for c in s:
if c == "(":
l += 1
elif c == ")":
if l:
l -= 1
else:
r += 1
ans = set()
n = len(s)
def dfs(i, l, r, lc, rc, t):
if i == n:
if l == 0 and r == 0:
ans.add(t)
return
if n - i < l + r or lc < rc:
return
if s[i] == "(" and l:
dfs(i + 1, l - 1, r, lc, rc, t)
if s[i] == ")" and r:
dfs(i + 1, l, r - 1, lc, rc, t)
dfs(i + 1, l, r, lc + (s[i] == "("), rc + (s[i] == ")"), t + s[i])
dfs(0, l, r, 0, 0, "")
return list(ans)
10/8 1021. 删除最外层的括号
left代表当前待匹配的左括号个数
cur为当前字符串
如果为0说明匹配完成 当前为一个原语
一个原语字符串首位字符必定为一左一右括号
去除左右两边括号即可
python
def removeOuterParentheses(s):
"""
:type s: str
:rtype: str
"""
ans = ""
cur = ""
left = 0
for c in s:
if c=="(":
left +=1
else:
left -=1
cur += c
if left ==0:
ans += cur[1:-1]
cur = ""
return ans
10/9 1541. 平衡括号字符串的最少插入次数
这里一个左括号必须配两个连续的右括号 '))'。
从左往右扫,记下还没配上的左括号个数。遇到 '(' 就多记一个。
遇到 ')' 时看下一个是不是也是 ')':是就配成一对往前走一步,不是就先插入一个 ')'。这时如果没有待配的左括号,再插入一个 '(',否则消耗一个左括号。
扫完后每个还没配上的左括号还要再插入两个 ')'。
python
def minInsertions(s):
"""
:type s: str
:rtype: int
"""
ans = x = 0
i, n = 0, len(s)
while i < n:
if s[i] == "(":
x += 1
else:
if i + 1 < n and s[i + 1] == ")":
i += 1
else:
ans += 1
if x == 0:
ans += 1
else:
x -= 1
i += 1
return ans + x * 2
10/10
python
10/11
python