150強訪談簡單

有效的括號字串

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

問題陳述

簡單

給定一個僅包含三種類型字元的字串 s:'('、')' 和 '*',如果 s 有效,則傳回 True。

以下規則定義有效字串:

- 任何左括號「(」必須有對應的右括號「)」。

- 任何右括號「)」必須有對應的左括號「(」。

- 左括號「(」必須位於對應的右括號「)」之前。

- '*' 可視為單一右括號 ')' 或單一左括號 '(' 或空字串。

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

約束條件
  • 1 <= len(s) <= 100
  • s contains only '(', ')' and '*'

範例

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

Matches perfectly.

Example 2
Input
s = "(*)"
Output
True
Explanation

Treat '*' as empty string.

Example 3
Input
s = "(*))"
Output
True
Explanation

Treat '*' as '('.

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

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