forked from sachuverma/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path24. Score of Parentheses.cpp
More file actions
47 lines (37 loc) · 867 Bytes
/
24. Score of Parentheses.cpp
File metadata and controls
47 lines (37 loc) · 867 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
39
40
41
42
43
44
45
46
47
/*
Score of Parentheses
====================
Given a balanced parentheses string S, compute the score of the string based on the following rule:
() has score 1
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: "()"
Output: 1
Example 2:
Input: "(())"
Output: 2
Example 3:
Input: "()()"
Output: 2
Example 4:
Input: "(()(()))"
Output: 6
Note:
S is a balanced parentheses string, containing only ( and ).
2 <= S.length <= 50
*/
class Solution {
public:
int scoreOfParentheses(string S) {
int ans = 0,count = 0, can_add = 0;
for(int i=0; i<S.size(); ++i){
if(S[i] == '(') count++,can_add = 1;
else {
count--;
if(can_add) ans += pow(2,count),can_add = 0;
}
}
return ans;
}
};