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

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