0
点赞
收藏
分享

微信扫一扫

LeetCode-Score of Parentheses


Description:
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

题意:计算一个只包含左右括号的字符串的”分数“,对分数的定义如下:

  • ():计算为1分
  • AB:计算为A的分数与B的分数的和,例如()()的分数为1+1=2
  • (A):计算为A的分数的两倍,例如(())的分数为1*2=2

解法:我们第一步要解决的是如果进行括号的匹配,很容易想到可以使用栈来实现;在第一步的基础上,我们来考虑怎么进行分数的计算;遍历字符串,将左括号入栈(为了处理方便,我使用-1表示左括号),每当遇到右括号时,有两种情况:

  • 如果是形如()()这种形式的,我们只需要匹配左括号,后将计算所得的分数1入栈
  • 如果是形如(())这种形式的,在我们第一次匹配了左括号后得到的结果为(1),这个时候我们需要将遇到左括号之前的所有数值进行累加得到结果1后,那么最终的分数为1*2,再将其结果入栈

在遍历完字符串后,栈中的结果为形如ABC,只需要将其中所有元素进行累加即可得到最后的分数;

Java

class Solution {
public int scoreOfParentheses(String S) {
Stack<Integer> parentheses = new Stack<>();
int result = 0;
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == '(') parentheses.push(-1);
else {
if (parentheses.peek() == -1) {
parentheses.pop();
parentheses.push(1);
continue;
}
int temp = 0;
while (parentheses.peek() > 0) temp += parentheses.pop();
parentheses.pop();
parentheses.push(temp * 2);
}
}
while (!parentheses.empty()) result += parentheses.pop();
return result;
}
}


举报

相关推荐

0 条评论