[LeetCode] 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

Note:

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

括号的分数。

给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:

() 得 1 分。
AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
(A) 得 2 * A 分,其中 A 是平衡括号字符串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/score-of-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

括号的题大多需要利用到stack的思路,这一题也不例外。题目的规则是对于一对单独的括号,他的值是1;对于嵌套的括号,嵌套内部的值就要 * 2;平行的括号对,他们的值是累加的。开始遍历input字符串,

  • 如果是左括号,则需要把之前已经计算好的结果入栈(否则会丢失),同时将res = 0以便记录当前这个括号内的结果
  • 如果是右括号,则需要开始结算。对于被当前这个右括号包括的所有内容,他的结果是被存在res的;但是由于当前这个右括号的外层有可能还有右括号,所以我们把此时栈顶元素也pop出来(如果有,说明还有外层)并加上当前层的res * 2。如果当前就是只有一层括号的话,那就只能加一

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int scoreOfParentheses(String S) {
 3         int res = 0;
 4         Stack<Integer> stack = new Stack<>();
 5         for (int i = 0; i < S.length(); i++) {
 6             char c = S.charAt(i);
 7             if (c == '(') {
 8                 stack.push(res);
 9                 res = 0;
10             } else {
11                 res = stack.pop() + Math.max(res * 2, 1);
12             }
13         }
14         return res;
15     }
16 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/14444855.html