File tree Expand file tree Collapse file tree 1 file changed +8
-12
lines changed
Expand file tree Collapse file tree 1 file changed +8
-12
lines changed Original file line number Diff line number Diff line change 33#include <algorithm>
44using namespace std;
55
6- // Function to calculate swaps required
6+
77long 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+
4743int main()
4844{
49- string s = "[]][ ][";
45+ string s = "[[]] ][";
5046 cout << swapCount(s) << "\n";
5147
5248 s = "[[][]]";
You can’t perform that action at this time.
0 commit comments