카테고리 없음
[LeetCode with Python] 20. Valid Parenthesis
papajohns
2020. 7. 1. 22:49
First Approach: use 'stack' and 'dictionary' to check correct parenthesis pair
from collections import deque
par_map = {')': '(', '}': '{', ']': '['}
class Solution:
def isValid(self, s: str) -> bool:
stack = deque()
for letter in s:
if letter not in par_map:
stack.append(letter)
else:
if not stack:
return False
elif stack[-1] == par_map[letter]:
stack.pop()
else:
return False
if stack:
return False
return True
Solution: use stack too, but also pythonic skills for efficiency
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
# The stack to keep track of opening brackets.
stack = []
# Hash map for keeping track of mappings. This keeps the code very clean.
# Also makes adding more types of parenthesis easier
mapping = {")": "(", "}": "{", "]": "["}
# For every bracket in the expression.
for char in s:
# If the character is an closing bracket
if char in mapping:
# Pop the topmost element from the stack, if it is non empty
# Otherwise assign a dummy value of '#' to the top_element variable
top_element = stack.pop() if stack else '#'
# The mapping for the opening bracket in our hash and the top
# element of the stack don't match, return False
if mapping[char] != top_element:
return False
else:
# We have an opening bracket, simply push it onto the stack.
stack.append(char)
# In the end, if the stack is empty, then we have a valid expression.
# The stack won't be empty for cases like ((()
return not stack