[LeetCode]#20. Valid Parentheses
2 min readOct 14, 2020
Environment: Python 3.7
Key technique: .pop, dictionary
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.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Analysis:
- Create a mapping dictionary
- input your test example
3–4. get first element in s for stack dictionary
5–6. get second in s and top_element is stack element.
7–8 check mapping dictionary is same as top_element
9 return your result
Solution:
class Solution(object):
def isValid(self, s):stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:stack.append(char)
return not stack
Submissions:
Reference:
Note:
Very hard to me and I need check reference….