856.括号的分数
思路:
![在这里插入图片描述](https://img-blog.csdnimg.cn/494f71484a2a42f5ab6f7f78e4295848.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5pivSmF2YeaWsOaJiw==,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
- 当遇到左括号时,0入栈
- 遇到右括号时,若栈顶为0,即栈顶为 左括号,弹出栈顶,1入栈;若栈顶不为0,则代表是(AB)情况,只需 使值相加 直至遇到栈顶为0,即为左括号
- 弹出此时栈顶的0,将 (相加的值*2) 入栈,因为是 (AB) 情况
- 此时栈中所有元素都是分数,全部求和即可
代码实现
class Solution {
public int scoreOfParentheses(String s) {
Stack<Integer> stack = new Stack<>();
for(char c : s.toCharArray()) {
if (c == '(') {
stack.push(0);
} else {
if (stack.peek() == 0) {
stack.pop();
stack.push(1);
} else {
int score = 0;
while (!stack.isEmpty() && stack.peek() != 0) {
score += stack.pop();
}
stack.pop();
stack.push(score << 1);
}
}
}
int sum = 0;
while (!stack.isEmpty()) {
sum += stack.pop();
}
return sum;
}
}