-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScoreOfBalancedExpression.cpp
More file actions
69 lines (57 loc) · 1013 Bytes
/
ScoreOfBalancedExpression.cpp
File metadata and controls
69 lines (57 loc) · 1013 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<string> s;
string S;
cin>>S;
// Stores index of
// character of string
int i = 0;
// Stores total scores
// obtained from the string
long long ans = 0;
// Iterate over characters
// of the string
while (i < S.length()) {
// If s[i] is '('
if (S[i] == '(')
s.push("(");
else {
// If top element of
// stack is '('
if (s.top() == "(") {
s.pop();
s.push("1");
}
else {
// Stores score of
// inner parentheses
long long count = 0;
// Calculate score of
// inner parentheses
while (s.top() != "(") {
// Update count
count += stoi(s.top());
s.pop();
}
// Pop from stack
s.pop();
// Insert score of
// inner parentheses
s.push(to_string(2 * count));
}
}
// Update i
i++;
}
// Calculate score
// of the string
while (!s.empty()) {
// Update ans
ans += stoi(s.top());
s.pop();
}
cout << ans;
}