Skip to content

Commit 00ab1ba

Browse files
authored
Refactored Score of Parentheses.java
1 parent 58ae069 commit 00ab1ba

File tree

1 file changed

+12
-22
lines changed

1 file changed

+12
-22
lines changed

Medium/Score of Parentheses.java

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,15 @@
11
class Solution {
2-
public static int scoreOfParentheses(String S) {
3-
Stack<String> st = new Stack<>();
4-
for (int i=0; i<S.length(); i++) {
5-
if (S.charAt(i) == '(') {
6-
st.push(String.valueOf(S.charAt(i)));
7-
}
8-
else {
9-
int num = 0;
10-
while (!st.peek().equals("(")) {
11-
num += Integer.parseInt(st.pop());
12-
}
13-
st.pop();
14-
st.push(num == 0 ? String.valueOf("1") : String.valueOf(2*num));
15-
}
16-
}
17-
18-
int ans = 0;
19-
while (!st.empty()) {
20-
ans += Integer.parseInt(st.pop());
21-
}
22-
23-
return ans;
2+
public int scoreOfParentheses(String S) {
3+
Stack<Integer> stack = new Stack<>();
4+
int currMultiplier = 0;
5+
for (char c : S.toCharArray()) {
6+
if (c == '(') {
7+
stack.push(currMultiplier);
8+
currMultiplier = 0;
9+
} else {
10+
currMultiplier = stack.pop() + Math.max(2 * currMultiplier, 1);
11+
}
2412
}
13+
return currMultiplier;
14+
}
2515
}

0 commit comments

Comments
 (0)