1963. Minimum Number of Swaps to Make the String Balanced
Difficulty: Medium
Topics: Two Pointers, String, Stack, Greedy
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.
A string is called balanced if and only if:
You may swap the brackets at any two indices any number of times.
Return the minimum number of swaps to make s balanced.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We can use a two-pointers approach, which is efficient given the constraints.
Track Balance: As we iterate through the string, we can track the balance between opening and closing brackets:
Identify Imbalance: When the balance becomes negative, it indicates that there are more closing brackets ']' than opening brackets '[' at that point in the string. This is where we need to swap brackets to make the string balanced.
Count Swaps: To correct an imbalance:
Let's implement this solution in PHP: 1963. Minimum Number of Swaps to Make the String Balanced
Explanation:
Balance Tracking:
- balance keeps track of the difference between the number of '[' and ']'.
- If balance becomes negative, it indicates that there are more ']' than '[' at that point.
Calculate Maximum Imbalance:
- max_imbalance stores the largest imbalance encountered during the iteration.
- If balance becomes negative, update max_imbalance with the larger of max_imbalance or -balance.
Calculate Swaps:
- To fix an imbalance, the minimum swaps required is (max_imbalance + 1) / 2.
Time Complexity:
This solution ensures that we meet the constraints, even for large inputs.
Contact Links
如果您發現本系列有幫助,請考慮在 GitHub 上給 存儲庫 一個星號或在您最喜歡的社交網絡上分享該帖子? 。您的支持對我來說意義重大!
如果您想要更多類似的有用內容,請隨時關注我:
Das obige ist der detaillierte Inhalt vonMindestanzahl an Swaps, um die Saite auszubalancieren. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!