forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain4.cpp
42 lines (33 loc) · 952 Bytes
/
main4.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
/// Source : https://leetcode.com/problems/score-of-parentheses/description/
/// Author : liuyubobobo
/// Time : 2018-06-25
#include <iostream>
#include <stack>
#include <cassert>
using namespace std;
/// Calculating Cores
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int scoreOfParentheses(string S) {
int balance = 0;
int res = 0;
for(int i = 0 ; i < S.size() ; i ++)
if(S[i] == '(')
balance ++;
else{
balance --;
if(S[i - 1] == '(')
res += (1 << balance);
}
return res;
}
};
int main() {
cout << Solution().scoreOfParentheses("()") << endl; // 1
cout << Solution().scoreOfParentheses("(())") << endl; // 2
cout << Solution().scoreOfParentheses("()()") << endl; // 2
cout << Solution().scoreOfParentheses("(()(()))") << endl; // 6
return 0;
}