2、括号的分数(90周)
题目描述:
思路都在代码的注释中,首先就是遇到左括号就入栈,遇到右括号需要注意的是判断栈顶是不是数字,如果是数字那么需要弹出数字,这里为了简化操作,栈里面的数字不会相邻,因此弹出数字后一定是左括号,弹出左括号,然后将弹出的值乘以2,之后我们需要判断此时栈顶是否为数字,因此要进行一下判断,如果是数字,弹出,并且加上之前乘以2的数字放入栈中,然后继续,如果是右括号,那么将左括号弹出的同时我们需要进行操作时要注意一下
注意栈中两个数字不允许相邻的条件。
我的代码
class Solution {
public int scoreOfParentheses(String S) {
if(S.length() == 0)
return 0;
//为了方便起见,左括号用0表示,右括号表示成-1
Stack<Integer> tem = new Stack<>();
for (int i = 0; i < S.length(); i++) {
//如果是左括号直接入栈
if(S.charAt(i) == '('){
tem.push(0);
}else {
//是右括号,需要注意,判断栈顶是不是数字
//如果栈顶是左括号
if(tem.peek() == 0){
tem.pop();
int tems = 1;
//如果栈顶是数字,要继续累加
if ( !tem.isEmpty() && tem.peek() != 0) {
tems += tem.pop();
}
tem.push(tems);
}else {
//如果栈顶是数字,那么需要弹出
int tems = tem.pop();
tems *= 2;
tem.pop();
//如果栈顶是数字,要继续累加
if ( !tem.isEmpty() && tem.peek() != 0) {
tems += tem.pop();
}
tem.push(tems);
}
}
}
return tem.peek();
}
}
排名靠前的代码
class Solution {
public int scoreOfParentheses(String S) {
int ans = 0, bal = 0;
for (int i = 0; i < S.length(); ++i) {
if (S.charAt(i) == '(') {
bal++;
} else {
bal--;
if (S.charAt(i-1) == '(')
ans += 1 << bal;
}
}
return ans;
}
}
我去,真简洁,而且效率也高,难受