Example 1
- Input
- s = "()"
- Output
- true
The single open bracket is closed by the matching close bracket.
Given a string of round, square and curly brackets, decide whether every opener is closed by the matching closer in the correct nested order. A stack of openers plus a closer-to-opener map settles it in one pass.
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid when open brackets are closed by the same type of bracket, open brackets are closed in the correct (innermost-first) order, and every close bracket matches an opener. The empty remainder after all matching pairs cancel is therefore the test for validity.
1 <= s.length <= 10^4s consists of parentheses only ()[]{}.The single open bracket is closed by the matching close bracket.
Each of the three pairs opens and closes in sequence.
The open bracket ( is closed by the wrong type ].
At the minimum allowed length, this opener has no closer. A one-character closer is invalid too; every valid string has even length.
After ( then [, the innermost unfinished opener is [. The next character ) expects (, so the nesting order is wrong despite equal counts for each type.
The inner [] closes first, then the outer () closes. Mixed types are valid when they obey this innermost-first order.
Think of openers as unfinished tasks stacked in nesting order. The next closer must finish the most recent unfinished task of the same type. In Example 1, ( creates one task and ) immediately finishes it. Counts alone miss the rule: ([)] has one pair of each type, but ) tries to finish the outer pair while [ is still waiting inside it.
Reveal Delete Inner Pairs: intuition, complexity, and code
"(((" never pops, so the non-empty stack at the end must return false.")()", has nothing to match and must return false."(]" passes a counting check but fails the type check on the stack top."([)]" is invalid despite equal counts; nested mixed types "([])" are valid."(()"."([)]"."(())": the first round replacement leaves "()", requiring another pass."()([)]" starts with a removable (), but its nonempty crossed remainder still makes the final answer false.A stack validates nested structure in one pass: openers wait on the stack and each closer settles exactly the most recent one.