forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
57 lines (45 loc) · 1.21 KB
/
main.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
54
55
56
57
/// Source : https://leetcode.com/problems/score-of-parentheses/description/
/// Author : liuyubobobo
/// Time : 2018-06-23
#include <iostream>
#include <stack>
#include <cassert>
using namespace std;
/// Recursive
/// Time Complexity: O(n^2)
/// Space Complexity: O(n)
class Solution {
public:
int scoreOfParentheses(string S) {
int res = 0;
int left = 0;
int start = 0;
for(int i = 0 ; i < S.size() ; i ++){
if(S[i] == '(')
left ++;
else{
left --;
if(left == 0){
res += score(S, start, i);
start = i + 1;
}
}
}
return res;
}
private:
int score(const string& s, int l, int r){
if(l + 1 == r){
assert(s[l] == '(' && s[r] == ')');
return 1;
}
return 2 * scoreOfParentheses(s.substr(l + 1, r - l + 1 - 2));
}
};
int main() {
cout << Solution().scoreOfParentheses("()") << endl;
cout << Solution().scoreOfParentheses("(())") << endl;
cout << Solution().scoreOfParentheses("()()") << endl;
cout << Solution().scoreOfParentheses("(()(()))") << endl;
return 0;
}