Given a string s containing just the characters '(', ')', '[', ']', '{' and '}', determine if the input string is valid. An input string is valid if every open bracket is closed by the same type of bracket and in the correct order.
s = "()"trues = "()[]{}"trues = "(]"falses = "{[]}"true()[]{}( [ { → push onto stackfalse (unmatched closer)falsestack.isEmpty() — true iff all opened brackets were closedStack mirrors nesting: the most recently opened bracket must be the first to close — LIFO is exactly the nesting order of brackets. Every time we hit a closer, the only valid matching opener is the one on top of the stack.
Just counting opening and closing brackets is not enough. In the second example the counts match, but the order is wrong.
The bracket opened last must be closed first. That is exactly how a stack works. When you see an opening bracket, push it. When you see a closing bracket, pop the top, and check that the pair matches. At the end, the stack must be empty.
Last opened, first closed, so use a stack. Push the expected closing bracket to make matching trivial.
Run the animation above on your own input, or watch the 1:37 video explanation of Valid Parentheses with a dry run and Java code.