競賽程式設計簡單

最小掉期括號平衡

“最小交換括號平衡”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 minimum_swaps_balancing(s),它接受由方括號 [] 組成的字串 s(其中包含相同數量的左括號和右括號),並傳回平衡該字串所需的相鄰字元交換的最小次數。

約束條件
  • 2 <= len(s) <= 10^5
  • s contains only '[' and ']'
  • Count of '[' equals count of ']'

範例

Example 1
Input
minimum_swaps_balancing('[]][[]')
Output
1
Explanation

Swap index 2 and 3 -> '[][][]', which is balanced. (1 swap)

Example 2
Input
minimum_swaps_balancing(']]][[[')
Output
6
Explanation

We can swap adjacent brackets to make it balanced, requiring 6 swaps in total.

Need a Hint?
考慮使用特定於貪婪的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。