Show problems as
Classic problem #20EasyStringStack

Valid Parentheses

Real-world version: Template Grouping Check
Tracked in this browser only
Read Valid Parentheses on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A template compiler scans a source file, discards every character that is not a grouping mark, and keeps what remains in order as the string code. So code is built only from round marks ( and ), square marks [ and ], and curly marks { and }. The compiler only runs this check on files that contained at least one grouping mark.

The compiler calls the grouping sound when the marks can be paired off so that all of the following hold:

  • Every mark belongs to exactly one pair.
  • In each pair, an opener comes first and a closer of the same shape comes later.
  • No two pairs cross: for any two pairs, one is either entirely inside the other or entirely outside it.

Return true when the grouping in code is sound, and false when no such pairing exists.

Examples

Example 1

Input
code = "([]{})"
Output
true

The square pair and the curly pair both sit entirely inside the round pair, so nothing crosses and every mark is used exactly once.

Example 2

Input
code = "{(})"
Output
false

Pairing the round marks and the curly marks here forces the two pairs to cross, and no other pairing is available.

Example 3

Input
code = "[[]"
Output
false

There are three marks, an odd count, so at least one cannot belong to a pair.

Example 4

Input
code = "]"
Output
false

A single closer has no opener before it to pair with.

Constraints

  • 1 <= code.length <= 10^4
  • `code` contains only the six characters `(`, `)`, `[`, `]`, `{`, `}`

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def is_balanced(code: str) -> bool:
Java
public boolean isBalanced(String code)