博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
856. Score of Parentheses(python+cpp)
阅读量:3702 次
发布时间:2019-05-21

本文共 2107 字,大约阅读时间需要 7 分钟。

题目:

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.

Example 1:

Input: "()" Output: 1

Example 2:

Input: "(())" Output: 2

Example 3:

Input: "()()" Output: 2

Example 4:

Input: "(()(()))" Output: 6

Note:

S is a balanced parentheses string, containing only ( and ).
2 <=S.length <= 50

解释:

这种括号的问题,一看就是用栈来做。
python代码:

class Solution(object):    def scoreOfParentheses(self, S):        """        :type S: str        :rtype: int        """        stack=[]        for s in S :            if s=='(':                stack.append(s)            else:                pre=stack.pop()                if pre=="(":                    stack.append(1)                else:                    current_sum=pre                    while stack[-1]!='(':                        current_sum+=stack.pop()                    stack.pop()                    stack.append(current_sum*2)        return sum(stack)

python的list没有变量类型的限制,可以随便放数字或者 char,但是c++的stack要设置类型的,怎么办?只能把(用数字0来表示。

c++代码:

#include
using namespace std;class Solution {
public: int scoreOfParentheses(string S) {
stack
_stack; for (auto s:S) {
if (s=='(') _stack.push(0); else {
int pre=_stack.top(); _stack.pop(); if (pre==0) _stack.push(1); else {
int cur_sum=pre; while(_stack.top()!=0) {
cur_sum+=_stack.top(); _stack.pop(); } _stack.pop(); _stack.push(2*cur_sum); } } } int result=0; while(!_stack.empty()) {
result+=_stack.top(); _stack.pop(); } return result; }};

解释:

转载地址:http://zwmcn.baihongyu.com/

你可能感兴趣的文章
git关联远程仓库--码云
查看>>
SpringBoot的单/多文件上传
查看>>
SQL语句大全
查看>>
SpringBoot安全管理 ——模块3:OAuth 2的简单应用
查看>>
SpringBoot消息服务 —— SpringBoot整合ActiveMQ
查看>>
Java 虚拟机 (JVM)系列一
查看>>
mybatis 中插入数据,如何获取到新增数据的主键 id
查看>>
SpringBoot + Vue 如何实现导出Excel操作,这篇文章帮你解决!
查看>>
IDEA访问不了官网解决办法
查看>>
Docker 基础篇之快速上手【一】
查看>>
Docker 基础篇之快速上手【二】
查看>>
【大厂面试】面试官都爱问的 Redis 事务
查看>>
IDEA编译时出现 Information:java: javacTask: 源发行版 1.8 需要目标发行版 1.8
查看>>
Redis 的 Java 客户端
查看>>
Redis 做分布式锁
查看>>
Redis 做消息队列
查看>>
Linux 的网络配置
查看>>
Linux 环境下安装 MySQL,各种踩坑、疑难杂症
查看>>
MySQL性能【索引优化分析】
查看>>
MySQL性能【查询截取分析】
查看>>