Post

[코테] 20. Valid Parentheses

난이도:EasySolved

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        
        # dictionay 문법으로 key:value 삽입 
        mapping = {")":"(", "}":"{", "]":"["} 

        for char in s:
		        # value에 존재한다면 stack에 푸쉬
            if char in mapping.values():
                stack.append(char)
            # key에 있다면 stack에 없거나 stack top에도 없으면 false
            elif char in mapping.keys():
                if not stack or mapping[char] != stack.pop():
                    return False
				# 마지막으로 비었는지 확인
        return not stack

Other Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
    def isValid(self, s: str) -> bool:
        st = []

        for i in range(len(s)):
            if st:
                last = st[-1]
                if self.is_pair(last, s[i]):
                    st.pop()
                    continue
            st.append(s[i])
        
        return not st
    
    def is_pair(self, last, cur):
        if last == "(" and cur == ")" or last == "{" and cur == "}" or last == "[" and cur == "]":
            return True
        return False
This post is licensed under CC BY 4.0 by the author.