File tree 1 file changed +8
-12
lines changed
1 file changed +8
-12
lines changed Original file line number Diff line number Diff line change 3
3
#include <algorithm>
4
4
using namespace std;
5
5
6
- // Function to calculate swaps required
6
+
7
7
long swapCount(string s)
8
8
{
9
- // Keep track of '['
10
9
vector<int> pos;
11
10
for (int i = 0; i < s.length(); ++i)
12
11
if (s[i] == '[')
13
12
pos.push_back(i);
14
13
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;
18
17
19
18
for (int i = 0; i < s.length(); ++i)
20
19
{
21
- // Increment count and move p to next position
20
+
22
21
if (s[i] == '[')
23
22
{
24
23
++count;
@@ -27,26 +26,23 @@ long swapCount(string s)
27
26
else if (s[i] == ']')
28
27
--count;
29
28
30
- // We have encountered an unbalanced part of string
29
+
31
30
if (count < 0)
32
31
{
33
- // Increment sum by number of swaps required
34
- // i.e. position of next '[' - current position
35
32
sum += pos[p] - i;
36
33
swap(s[i], s[pos[p]]);
37
34
++p;
38
35
39
- // Reset count to 1
40
36
count = 1;
41
37
}
42
38
}
43
39
return sum;
44
40
}
45
41
46
- // Driver code
42
+
47
43
int main()
48
44
{
49
- string s = "[]][ ][";
45
+ string s = "[[]] ][";
50
46
cout << swapCount(s) << "\n";
51
47
52
48
s = "[[][]]";
You can’t perform that action at this time.
0 commit comments