forked from shijbian/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscore-of-parentheses.cpp
More file actions
38 lines (36 loc) · 864 Bytes
/
score-of-parentheses.cpp
File metadata and controls
38 lines (36 loc) · 864 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
33
34
35
36
37
38
// Time: O(n)
// Space: O(1)
class Solution {
public:
int scoreOfParentheses(string S) {
int result = 0, depth = 0;
for (int i = 0; i < S.length(); ++i) {
if (S[i] == '(') {
++depth;
} else {
--depth;
if (S[i - 1] == '(') {
result += 1 << depth;
}
}
}
return result;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
int scoreOfParentheses(string S) {
vector<int> stack(1, 0);
for (const auto& c : S) {
if (c == '(') {
stack.emplace_back(0);
} else {
const auto last = stack.back(); stack.pop_back();
stack.back() += max(1, 2 * last);
}
}
return stack.front();
}
};