Python 基礎知識簡單

平衡括號問題

「平衡括號問題」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 is_balanced(s) ,它接受僅包含字元 '(', ')', '{', '}', '[' 和 ']' 的字串 s ,如果括號平衡且正確嵌套,則傳回 True ,否則傳回 False 。空字串被認為是平衡的。

約束條件
  • 0 <= len(s) <= 10^4
  • s consists only of '(', ')', '{', '}', '[', ']'

範例

Example 1
Input
s = '({[]})'
Output
True
Explanation

Each opening bracket has a matching closing bracket in the correct order: ( matches ), { matches }, [ matches ].

Example 2
Input
s = '({[})'
Output
False
Explanation

The [ is closed by } which is a mismatch.

Example 3
Input
s = ''
Output
True
Explanation

An empty string is considered balanced.

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 資源

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