https://leetcode.com/problems/valid-parentheses/submissions/

 

Valid Parentheses - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def isValid(self, s: str-> bool:
        stack = []
        table = {
            ')':'(',
             '}':'{',
             ']':'['
             }
        for char in s:
            if char not in table:
                stack.append(char)
            elif not stack or table[char] != stack.pop():
                return False
                
        return len(stack) == 0
cs

1.
stack = [ '(',  '(',  '{' ] 이 있다면, 다음에 올 문자는 '('  '{'  '[' 을 제외하고는 '}' 만 올 수 있다.
정리하자면, 여는 기호를 제외하고는 stack[-1] 의 닫는 기호가 와야한다. != 로 비교함과 동시에 pop()을 한다.
복잡하게 생각할 것 없이 마지막 항만 고려해서 순차적으로 풀면 된다.


2.
닫는 기호가 빈 stack 에 들어가도 False

+ Recent posts