프로그래밍/Algorithm

짝이맞지않는괄호 파이썬

모지사바하 2022. 1. 7. 10:37
def solution(brackets):
    o = '({['
    c = ')}]'
    if brackets[0] in c:
        return False

    if brackets[-1] in o:
        return False

    if len(brackets) % 2 == 1:
        return False

    s = []

    for b in brackets:
        if b in o:
            s.append(b)
        if b in c:
            if s[-1] in o and o.index(s[-1]) == c.index(b):
                s.pop()
            else:
                return False

    return len(s) == 0


print(solution('({[}])'))

# 3
# ()()
# ({[}])
# ({}[(){}])

 

 

갑자기 문득 예전에 풀었던게 떠올라서 풀어봤다.

 

쉽다

 

열린괄호 닫힌괄호를 따로 정의해준후, 

닫힌 괄호일때 stack 의 마지막에 있는 열린괄호와 같은 index인지 검사하고 같다면 pop

 

다르면 False 리턴