150強訪談簡單

有效括號

“有效括號”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個只包含字元 '('')''{''}''['']' 的字串 s,確定輸入字串是否有效。

輸入字串在以下情況下有效:

1. 左括號必須由相同類型的括號封閉。

2. 左括號必須以正確的順序閉合。

3. 每個閉括號都有一個對應的相同類型的開括號。

寫一個函數 isValid(s: str) -> bool

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

範例

Example 1
Input
s = "()"
Output
True
Explanation

A single pair of matching parentheses is valid.

Example 2
Input
s = "()[]{}"
Output
True
Explanation

Three pairs of matching brackets, each closed in order.

Example 3
Input
s = "(]"
Output
False
Explanation

Opening '(' is closed by ']' which is the wrong type.

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

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