forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
46 lines (36 loc) · 1021 Bytes
/
main3.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
/// Source : https://leetcode.com/problems/score-of-parentheses/description/
/// Author : liuyubobobo
/// Time : 2018-06-25
#include <iostream>
#include <stack>
#include <cassert>
using namespace std;
/// Using a Stack
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
int scoreOfParentheses(string S) {
stack<int> stack;
stack.push(0);
for(char c: S){
if(c == '(')
stack.push(0);
else{
int v = stack.top();
stack.pop();
int w = stack.top();
stack.pop();
stack.push(w + max(2 * v, 1));
}
}
return stack.top();
}
};
int main() {
cout << Solution().scoreOfParentheses("()") << endl; // 1
cout << Solution().scoreOfParentheses("(())") << endl; // 2
cout << Solution().scoreOfParentheses("()()") << endl; // 2
cout << Solution().scoreOfParentheses("(()(()))") << endl; // 6
return 0;
}