forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScoreOfParentheses.java
38 lines (35 loc) · 1.05 KB
/
ScoreOfParentheses.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
// TC : O(n)
// SC : O(n) => ()()()() => n/2
public int scoreOfParentheses(String s) {
Stack<String> st = new Stack<>();
for(int i =0; i<s.length();i++){
char c = s.charAt(i);
if(st.empty()){
st.push(c + "");
} else {
if(c == ')'){
int innerScore = 0;
while(!st.empty() && !st.peek().equals("(")){
innerScore += Integer.valueOf(st.peek());
st.pop();
}
st.pop();
if(innerScore == 0){ //()
st.push("1");
} else{
st.push(2*innerScore + "");
}
} else{
st.push(c + "");
}
}
}
int score = 0;
while(!st.empty()){ // ()()() // 1 1 1
score += Integer.valueOf(st.peek());
st.pop();
}
return score;
}
}