#C6754. Balanced Parentheses Checker

    ID: 50549 Type: Default 1000ms 256MiB

Balanced Parentheses Checker

Balanced Parentheses Checker

You are given an expression in the form of a string that may contain various characters including parentheses. Your task is to determine whether the parentheses in the expression are balanced. An expression is said to have balanced parentheses if every opening parenthesis ( has a corresponding closing parenthesis ) in the correct order.

The balance condition can be formally represented as follows: if we scan the expression from left to right, the number of closing parentheses should never exceed the number of opening parentheses, and at the end, the two counts should be equal. In mathematical notation, this can be written as:

$$\forall i,\; \#(\text{before }i)(\geq \#)(\text{before }i) \quad \text{and} \quad \#(\text{total }() = \#)(\text{total }())$$

For example:

  • 3 + (4 * (5 - 2)) is balanced.
  • 3 + (4 * (5 - 2) is not balanced because it is missing a closing parenthesis.
  • 3 + 4) * (5 - 2) is not balanced because it has an extra closing parenthesis.

Your solution should read the expression from standard input and output either True or False (without quotes) indicating whether the expression is balanced.

inputFormat

A single line string representing the expression to be checked. The expression may contain spaces and other characters.

outputFormat

Print 'True' if the input expression has balanced parentheses; otherwise, print 'False'.## sample

3 + (4 * (5 - 2))
True