5th LeetCode: Valid Parentheses
Solution 1
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
This is the extension of the last try. Only that this time we only have to check the validity of the input string.
The solution is like this:
- Create a list for left parentheses
- Scan from the LHS to the RHS of the string:
a. Store the scanned character in the list if the scanned character is “(” or ”[” or “{”
b. Compare the last stored character in the list if the scanned character is a right parenthesis:
b-1. If the two are the same type, pop out the left parenthesis from the list
b-2. Else, return False - Return True if the scan completed
https://leetcode.com/problems/valid-parentheses/discuss/603002/Python-3-simple-scanning-with-loop