856. Score of Parentheses

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

计算由"("和")"组成的字符串的值。嵌套:乘2,并列:相加

用stack就可以。"("入栈,")",往前搜索第一个"(",如果中间有数字的,取出数字求和并乘以2;如果没有数字,直接压入"1"。

最后把stack中所有的数字相加。

 1 class Solution {
 2 public:
 3     int scoreOfParentheses(string S) {
 4         stack<string> s;
 5         int i = 0;
 6         while (i < S.length()) {
 7             if (S[i] == '(')
 8                 s.push("(");
 9             else {
10                 if (s.top() == "(") {
11                     s.pop();
12                     s.push("1");
13                 }
14                 else {
15                     int temp = 0;
16                     while (s.top() != "(") {
17                         temp += stoi(s.top());
18                         s.pop();
19                     }
20                     s.pop();
21                     s.push(to_string(2 * temp));
22                 }
23             }
24             ++i;
25         }
26         int res = 0;
27         while (!s.empty()) {
28             res += stoi(s.top());
29             s.pop();
30         }
31         return res;
32     }
33 };

 

转载于:https://www.cnblogs.com/Zzz-y/p/9221472.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值