Valid parentheses
The string s is made only of the bracket characters (, ), [, ], { and }. Return True if its brackets are matched, and False if they are not.
Matched means this. Read s from left to right. Each closing bracket must close the most recent opening bracket that is still open, and the two must be the same kind: ( with ), [ with ], { with }. A closing bracket that arrives with nothing open breaks the rule. When the string ends, no opening bracket may still be open.
So ([)] is not matched, even though each kind opens once and closes once. The empty string has nothing to close, so it is matched.
s = "([]{})"OutputTrueThe [] and the {} each close inside the ( ), and the ) closes last.
s = "([)]"OutputFalseThe ) arrives while [ is the most recent bracket still open.
s = "{[]"OutputFalseThe [] matches, but the { is never closed.
0 ≤ len(s) ≤ 2 × 105
Every character is one of
( ) [ ] { }.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.