forked from sachuverma/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCount the Reversals.cpp
72 lines (63 loc) · 1.43 KB
/
Count the Reversals.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
Count the Reversals
===================
Given a string S consisting only of opening and closing curly brackets '{' and '}' find out the minimum number of reversals required to make a balanced expression.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases
follow. The first line of each test case contains a string S consisting only of { and }.
Output:
Print out minimum reversals required to make S balanced. If it cannot be balanced, then print -1.
Constraints
1 <= T <= 100
0 <= |S| <= 50
Examples
Input:
4
}{{}}{{{
{{}}}}
{{}{{{}{{}}{{
{{{{}}}}
Output:
3
1
-1
0
Explanation:
Testcase 1: For the given string }{{}}{{{ since the length is even we just need to count the number of openning brackets('{') suppose denoted by 'm' and closing brackest('}') suppose dentoed by 'n' after removing highlighted ones. After counting compute ceil(m/2) + ceil(n/2).
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
string s;
cin >> s;
int left = 0, right = 0;
for (auto &i : s)
{
if (i == '{')
left++;
else
{
if (left == 0)
right++;
else
left--;
}
}
if ((left + right) % 2)
cout << -1 << endl;
else
{
int ans = 0;
if (left % 2)
ans = 2;
ans += left / 2 + right / 2;
cout << ans << endl;
}
}
return 0;
}