awelgorithms

Reject a mismatched closer

Updated

If the closer does not match the top opener, the string is invalid. Do not pop hoping it works later. Empty stack plus a closer is also a mismatch (nothing to close).

What to focus on

"(]" : top is '(', closer is ']' — reject. ")" : empty, closer — reject. After reject you can stop. Further characters cannot fix a wrong closer.

Worked examples

wrong type

s = "(]"
  1. push (
  2. see ]
  3. top ( is not [

Result: invalid

closer first

s = ")"
  1. stack empty
  2. nothing to pop

Result: invalid

nested wrong

s = "([)]"
  1. push ( [
  2. see )
  3. top is [ not (

Result: invalid

Try it

Write isValid(s). s is a string of bracket characters. Return false at the first closer that does not match the top, or if the stack is empty when a closer arrives. Do not keep walking after a mismatch. "(]", ")", and "([)]" fail at the first bad closer.

s is a string of bracket characters. Mismatch is in scope. That is this skill. Stop at the first bad closer.