LeetCode 856. Score of Parentheses解题报告(python)

本文介绍了一种使用Python解决括号字符串分数计算问题的方法。通过分析()()与(())在计算分数时的不同规则,提出了一种利用栈思想的解决方案。对于连续的')',需要将分数翻倍;对于'('和')',需要进行配对。最终,通过一个Solution类的scoreOfParentheses方法实现了这一算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

856. Score of Parentheses

  1. Score of Parentheses python solution

题目描述

Given a balanced parentheses string S, compute the score of the string based on the following rule:
() has score 1
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.

在这里插入图片描述

解析

关键的区别在于()()需要将个数加1,但是(())需要将个数乘以2。所以当出现连续’)‘的时候需要翻倍
同时需要对应’(‘和’)’,需要引入stack的思想。

class Solution:
    def scoreOfParentheses(self, S: str) -> int:
        stack,cur=[],0
        for i in S:
            if i=='(':
                stack.append(cur)
                cur=0
            else:
                cur+=stack.pop()+max(cur,1)
        return cur

Reference

https://leetcode.com/problems/score-of-parentheses/discuss/141777/C%2B%2BJavaPython-O(1)-Space

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值