Skip to content

Commit 27cbebf

Browse files
authored
Update Minimum_swaps_for_bracket_balancing
1 parent 120cf05 commit 27cbebf

File tree

1 file changed

+8
-12
lines changed

1 file changed

+8
-12
lines changed

Greedy/Minimum_swaps_for_bracket_balancing

+8-12
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,21 @@
33
#include <algorithm>
44
using namespace std;
55

6-
// Function to calculate swaps required
6+
77
long swapCount(string s)
88
{
9-
// Keep track of '['
109
vector<int> pos;
1110
for (int i = 0; i < s.length(); ++i)
1211
if (s[i] == '[')
1312
pos.push_back(i);
1413

15-
int count = 0; // To count number of encountered '['
16-
int p = 0; // To track position of next '[' in pos
17-
long sum = 0; // To store result
14+
int count = 0;
15+
int p = 0;
16+
long sum = 0;
1817

1918
for (int i = 0; i < s.length(); ++i)
2019
{
21-
// Increment count and move p to next position
20+
2221
if (s[i] == '[')
2322
{
2423
++count;
@@ -27,26 +26,23 @@ long swapCount(string s)
2726
else if (s[i] == ']')
2827
--count;
2928

30-
// We have encountered an unbalanced part of string
29+
3130
if (count < 0)
3231
{
33-
// Increment sum by number of swaps required
34-
// i.e. position of next '[' - current position
3532
sum += pos[p] - i;
3633
swap(s[i], s[pos[p]]);
3734
++p;
3835

39-
// Reset count to 1
4036
count = 1;
4137
}
4238
}
4339
return sum;
4440
}
4541

46-
// Driver code
42+
4743
int main()
4844
{
49-
string s = "[]][][";
45+
string s = "[[]]][";
5046
cout << swapCount(s) << "\n";
5147

5248
s = "[[][]]";

0 commit comments

Comments
 (0)