알고리즘

<백준> 4949번 파이썬 알고리즘

changha. 2021. 7. 10. 14:28
while True:
    a = input()
    stk = []
    
    if a == ".":
        break 

    for i in a:
        if i == "[" or i == "(":
            stk.append(i)
        elif i == "]":
            if len(stk) != 0 and stk[-1] == "[":
                stk.pop()
            else:
                stk.append("]")
                break
        elif i == ")":
            if len(stk) != 0 and stk[-1] == "(":
                stk.pop()
            else:
                stk.append(")")
                break 
    if len(stk) == 0:
        print("yes")
    else:
        print("no")

[ or ( 일때는 append 해준다

만약 ] or ) 일때는 stack의 마지막 원소가 짝이 맞을 때 pop을 해준다

그렇지 않을때는 그대로 삽입해준다 

 

반복이 끝나고 

stack이 0 이아니면 짝이 맞지 않으므로 no