-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimum_Swaps_for_Bracket_Balancing.cpp
More file actions
73 lines (65 loc) · 2.1 KB
/
Copy pathMinimum_Swaps_for_Bracket_Balancing.cpp
File metadata and controls
73 lines (65 loc) · 2.1 KB
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
73
// ! Date :- 03-10-2022
// * https://practice.geeksforgeeks.org/problems/minimum-swaps-for-bracket-balancing2704/1
class Solution
{
public:
int minimumNumberOfSwaps(string S)
{
vector<int> pos;
for (int i = 0; i < s.length(); ++i)
if (s[i] == '[')
pos.push_back(i);
int openingBrace = 0;
int nextPos = 0; // give the position of the next opening brace by which we perform swap operation
long totalSwaps = 0;
for (int i = 0; i < s.length(); ++i)
{
// Increment openingBrace and move nextPos to next position
if (s[i] == '[')
{
++openingBrace;
++nextPos;
}
else if (s[i] == ']')
--openingBrace;
// We have encountered an unbalanced part of string
// since the number of opening brackets and closing brackets are same
// thus we make sure that we have at least one opening bracket after current index.
if (openingBrace < 0)
{
// Increment totalSwaps by number of swaps required
totalSwaps += pos[nextPos] - i;
swap(s[i], s[pos[nextPos]]);
// increment the nextPos because curr nextPos '[' can't help us another time to balancing the string
++nextPos;
// Reset openingBrace to 1
openingBrace = 1;
}
}
return totalSwaps;
}
};
class Solution
{
public:
int minimumNumberOfSwaps(string S)
{
// code here
int openBraces = 0, closeBrace = 0;
int extraClose = 0;
int swaps = 0;
for (const char &x : S)
if (x == '[')
{
++openBraces;
if (extraClose > 0) // only if we have extra close braces then swap it with current opening brace
swaps += extraClose--;
}
else
{
++closeBrace;
extraClose = closeBrace - openBraces;
}
return swaps;
}
};