Friday, November 9, 2018
856. Score of Parentheses
Version #1 Stack
100.00 %
class Solution {
public int scoreOfParentheses(String S) {
if (S == null || S.length() == 0) {
return 0;
}
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < S.length(); i++) {
char curr = S.charAt(i);
// (() (()))
// -1 1 2
if (curr == '(') {
stack.addFirst(-1);
} else {
int sum = 0;
if (stack.getFirst() == -1) {
// ()
stack.removeFirst();
sum = 1;
} else {
// ( x )
while (!stack.isEmpty() && stack.getFirst() != -1) {
sum += stack.removeFirst();
}
sum = sum * 2;
stack.removeFirst();
}
stack.addFirst(sum);
}
}
int result = 0;
while (!stack.isEmpty()) {
result += stack.removeFirst();
}
return result;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment