-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_30.java
More file actions
29 lines (25 loc) · 838 Bytes
/
Problem_30.java
File metadata and controls
29 lines (25 loc) · 838 Bytes
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
package strings;
// Minimum number of swaps for bracket balancing.
public class Problem_30 {
public static int minSwaps(String str) {
int countOpen = 0;
int countClose = 0;
for (char ch : str.toCharArray()) {
if (ch == '[') {
countOpen++;
} else if (ch == ']') {
if (countOpen > 0) {
countOpen--; // Balanced an opening bracket
} else {
countClose++; // Extra closing bracket
}
}
}
return countOpen + countClose; // Minimum number of swaps
}
public static void main(String[] args) {
String str = "]]][[[[";
int minSwaps = minSwaps(str);
System.out.println("Minimum swaps required for balancing: " + minSwaps);
}
}