-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathScore of Parentheses.cpp
53 lines (38 loc) · 1.16 KB
/
Score of Parentheses.cpp
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Solution by Rahul Surana
***********************************************************
Given a balanced parentheses string s, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
"()" has score 1.
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
int scoreOfParentheses(string s) {
if(s.length() == 0) return 0;
int ans = 0;
stack<int> st;
st.push(0);
for(int i = 0; i < s.length(); i++){
if(s[i] == '('){
st.push(0);
}
else{
int x = st.top();
st.pop();
int val = 0;
if(x > 0){
val = x*2;
}
else{
val = 1;
}
st.top() += val;
}
}
return st.top();
}
};