본문 바로가기
Leetcode

20. Valid Parentheses

by YGSEO 2020. 7. 21.
728x90
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

hash map을 만들어서  string의 element를 stack

element가 open이면 stack에 넣고 closing이면 stack.pop을 사용해서 top_element 변수를 만들어서 hash map 매칭해서 같은 종류의 opening bracket 인지 여부를 판단.

 

class Solution:
    def isValid(self, s: str) -> bool:
        opened = ['[', '(', '{']
        closed = [']', ')', '}']
        stack = []
        for c in s:
            if c in opened:
                stack.append(c)
            else:
                if len(stack) != 0 and stack[-1] == opened[closed.index(c)]:
                    stack.pop()
                else:
                    return False
        return len(stack) == 0
728x90

'Leetcode' 카테고리의 다른 글

739. Daily Temperatures  (0) 2020.08.03
921. Minimum Add to Make Parentheses Valid  (0) 2020.07.22
844. Backspace String Compare  (0) 2020.07.21
682. Baseball Game  (0) 2020.07.19
496. Next Greater Element I  (0) 2020.07.06

댓글