[LeetCode]#20. Valid Parentheses

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:

  1. Open brackets must be closed by the same type of brackets.
  2. 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:

  1. Create a mapping dictionary
  2. 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….

Interesting in any computer science.