解题思路
栈模拟。
相关代码
class Solution {
public int scoreOfParentheses(String s) {
//stack中的值是左括号的的右边所有合法配对括号的值
Stack<Integer> stack = new Stack<>();
stack.push(0);
for(int i=0;i<s.length();i++)
if(s.charAt(i) == '(') stack.push(0);
else{
int t = stack.pop();
int k = stack.pop();
if(t == 0) stack.push(k+t+1);
else stack.push(k+t*2);
}
return stack.peek();
}
}