본문 바로가기

leetcode

[leetcode] 20. Valid Parentheses (easy)

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {'(':')', '{':'}', '[':']'}
        stack = []
        for c in s:
            # print ('c is', c)
            if c in ['(','{','[']:
                stack.append(c)
            else:
                if len(stack) == 0:
                    return False
                pop = stack.pop()
                if dic[pop] == c:
                    continue
                else:
                    return False
        if len(stack) > 0:
            return False
        return True

[문제]

규칙에 맞게 괄호 여닫는게 제대로 되어 있는 지 확인하는 문제

 

[풀이]

stack을 이용해서 해결

- 여는 괄호가 나오면 push

- 닫는 괄호가 나오면 pop

- 마지막에 stack에 괄호가 남아 있다면 False

- 마지막에 stack에 남는 게 없어야 한다