0020. Valid Parentheses
Easy | String + Stack | 24 ms (95.97%), 14.3 MB (64.31%)
Last updated
Was this helpful?
Easy | String + Stack | 24 ms (95.97%), 14.3 MB (64.31%)
Last updated
Was this helpful?
Source: GitHub:
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
return False if first char is a right-side parenthesis
return False if the stack is already empty but there is an incoming parenthesis
return False if the incoming parenthesis doesn't match with the popped item
Note that we need to check whether the stack is empty before returnning the answer. If the stack is not empty but there are no incoming parentheses, return False.