0020. Valid Parentheses
Easy | String + Stack | 24 ms (95.97%), 14.3 MB (64.31%)
Source: LeetCode - Valid Parentheses GitHub: Solution / Performance
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.
Use the hash table to record the mapping of parentheses and the stack to store left-side parenthesis for further verification when meeting right-side parenthesis.
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.
Last updated