Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
Solution
We use a stack data structure to do this.
- Keep track of matching opening and closing brackets using a hashmap.
- Given an opening bracket, we add it to the stack.
- Given a closing bracket, we check whether the top of stack has the correctly matching opening bracket (and whether the stack exists).
- If it is correct, we can pop it from the stack and continue to the next bracket.
- If it is incorrect we can return False.