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

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。