给定一个平衡括号字符串
S
,按下述规则计算该字符串的分数:
()
得 1 分。AB
得A + B
分,其中 A 和 B 是平衡括号字符串。(A)
得2 * A
分,其中 A 是平衡括号字符串。
示例 1:
输入: "()" 输出: 1示例 2:
输入: "(())" 输出: 2示例 3:
输入: "()()" 输出: 2示例 4:
输入: "(()(()))" 输出: 6
难度---简单
class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
stack = [0]
l = len(S)
if l<2 or l>50:
return 0
for s in S:
if s =="(":
stack.append(0)
else:
top_element = stack.pop()
if top_element ==0:
stack[-1] += 1
else:
stack[-1] += 2*top_element
return stack.pop()
成功
执行用时: 36 ms, 在Score of Parentheses的Python提交中击败了3.33% 的用户
内存消耗: 10.6 MB, 在Score of Parentheses的Python提交中击败了0.00% 的用户
但是我自己写了一个测试用例,是不会通过的
已完成
执行用时: 24 ms
输入 "(()"
输出 1
预期结果 2
预期和结果不相同,分析原因是,平衡符号是单数,有一个括号不回匹配成功。这一点没有考虑进去。
明天好好解决一下,然后将 有效的括号---LeetCode----(12) 重做一遍。 20190304 22:31
----------------------------------------------------------------------------分割线-----------------------------------------------------------------------------------