-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0856.cpp
More file actions
32 lines (30 loc) · 734 Bytes
/
Copy path0856.cpp
File metadata and controls
32 lines (30 loc) · 734 Bytes
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
// Stack solution
class Solution {
public:
int scoreOfParentheses(const string &s) {
stack<int> st;
int score = 0;
for (const char c : s) {
if (c == '(')
st.push(score), score = 0;
else {
score = score ? 2 * score : 1;
score += st.top();
st.pop();
}
}
return score;
}
};
// O(1) memory solution
class Solution {
public:
int scoreOfParentheses(const string &s) {
int res = 0, l = 0;
for (int i = 0; i < s.size(); i++) {
l += s[i] == '(' ? 1 : -1;
if (s[i] == ')' && s[i - 1] == '(') res += 1 << l;
}
return res;
}
};