-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscoreOfParentheses.cpp
More file actions
50 lines (48 loc) · 1.09 KB
/
scoreOfParentheses.cpp
File metadata and controls
50 lines (48 loc) · 1.09 KB
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
class Solution {
public:
inline int get(char c) {
return (c == '(') ? -1 : -2;
}
int scoreOfParentheses(string s) {
stack<int> st;
for (char c: s) {
if (get(c) == -1) {
st.push(-1);
}
else {
int t = 0;
while (st.top() != -1) {
t += st.top();
st.pop();
}
st.pop();
if (t) {
st.push(2 * t);
}
else {
st.push(1);
}
}
}
int ans = 0;
while (!st.empty()) {
ans += st.top();
st.pop();
}
return ans;
}
};
// depth and contriutions of "()"
class Solution {
public:
int scoreOfParentheses(string s) {
int ans = 0, d = 0;
for(int i = 0; i < s.size(); ++i) {
d += s[i] == '(' ? 1 : -1;
if(s[i] == ')' && s[i - 1] == '(') {
ans += 1 << d;
}
}
return ans;
}
};