Untitled
unknown
java
10 days ago
1.1 kB
2
Indexable
Never
public class BalanceParentheses { public static int minimumSwaps(String brackets) { int n = brackets.length(); char[] s = brackets.toCharArray(); // Check if the total number of '(' and ')' are equal int totalLeft = 0, totalRight = 0; for (char c : s) { if (c == '(') totalLeft++; else totalRight++; } if (totalLeft != totalRight) return -1; int swaps = 0, imbalance = 0; int countLeft = 0, countRight = 0; for (char c : s) { if (c == '(') { countLeft++; if (imbalance > 0) { swaps += imbalance; imbalance--; } } else { countRight++; imbalance = countRight - countLeft; } } return swaps; } public static void main(String[] args) { String brackets = "()())"; int result = minimumSwaps(brackets); System.out.println(result); // Expected output: 1 } }
Leave a Comment