20221009 - 856. Score of Parentheses 括号的分数(栈)

44 阅读1分钟

Given a balanced parentheses string s, return the score of the string.

The score of a balanced parentheses string is 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: s = "()"
Output: 1

Example 2

Input: s = "(())"
Output: 2

Example 3

Input: s = "()()"
Output: 2

Constraints

  • 2 <= s.length <= 50
  • s consists of only '(' and ')'.
  • s is a balanced parentheses string.

Solution

用一个栈来存每一个括号内算出来的分数

最最开始压入一个 0 ,最后弹出的分数就会更新在这个栈底元素上

每次遇到左括号就把 0 压入栈,这个 0 的含义是当前左括号所对应一对括号内的分数,之后都会更新

每次遇到右括号就把栈顶元素弹出,在弹出后的栈顶元素上加上弹出元素所表示的分数:

  • 弹出的如果是 0 说明跟当前右括号对应的一对括号内分数为 0 (原因见上一行入栈 0 的定义),给弹出后的栈顶元素 +1
  • 弹出的如果不是 0 说明当前括号内对应的一对括号内的分数最后会翻倍,* 2 以后加给弹出后的栈顶元素
  • 代码实现为弹出的元素 > 0 就给栈顶元素 + 2 * v ;弹出的元素 == 0 就给栈顶元素 +1

遍历字符串结束后弹出栈底元素(此时栈内就这一个元素)

int scoreOfParentheses(char * s){
    int i, v, top, stack[50];
    top = 0;
    stack[top++] = 0;
    for (i = 0; s[i]; i++) {
        if (s[i] == '(') {
            stack[top++] = 0;
        } else {
            v = stack[--top];
            stack[top - 1] += 2 * v > 1 ? 2 * v : 1;
        }
    }
    return stack[top - 1];
}

计算最终分数和

对于一个括号可以计算他的深度 bal ,对应括号最终的分数就是 2bal

首先初始化 bal 和 ans 为 0

遍历字符串,对于当前字符做如下判断:

  • 如果当前字符为左括号,bal++ ;如果当前字符为右括号,bal--
  • 如果当前字符为右括号且前一个字符为左括号,计算该最小括号对的最终分数并加到 ans 上;如果当前字符为左括号进入下一轮循环
int scoreOfParentheses(char * s){
    int i, bal, ans;
    ret = bal = 0;
    for (i = 0; s[i]; i++) {
        bal += (s[i] == '(') ? 1 : -1;
        if (s[i] == ')' && s[i - 1] == '(')
            ans += 1 << bal;
    }
    return ans;
}

题目链接:856. 括号的分数 - 力扣(LeetCode)