LC 856. Score of Parentheses

Posted ethanhong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 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

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Score of Parentheses.

(A) = 2 * A 是表示深度的一个概念。

 

class Solution {
public:
  int scoreOfParentheses(string S) {
    int ret = 0, cnt = 0;
    char last =  ;
    for(auto ch : S){
      if(ch == (){
        cnt++;
      }else {
        cnt--;
        if(last == (){
          ret += (1<<cnt);
        }
      }
      last = ch;
    }
    return ret;
  }
};

 

以上是关于LC 856. Score of Parentheses的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 856. Score of Parentheses

Leetcode 856. Score of Parentheses 括号得分(栈)

856. Score of Parentheses

leetcode 856. 括号的分数(Score of Parentheses)

力扣 每日一题 856. 括号的分数难度:中等(栈 / 思维计数&括号深度)

力扣 每日一题 856. 括号的分数难度:中等,rating: 1562(栈 / 思维计数&括号深度)