리셋 되지 말자

[백준 4949] 균형잡힌 세상 - 스택 본문

알고리즘

[백준 4949] 균형잡힌 세상 - 스택

kyeongjun-dev 2022. 1. 18. 14:42

코드

def solution(string):
    stack = []
    no_sts = False
    for char in string:
        # print(stack)
        # 여는 괄호('[', '('가 나오면 stack에 추가
        if char == '[' or char == '(':
            stack.append(char)
        # 닫는 괄호(']', ')'가 나오면 예외처리
        elif char == ']' or char == ')':
            # 닫는 괄호인데 스택이 비어있으면 no
            if len(stack) == 0:
                no_sts = True
                break
            else:
                # 닫는 괄호와 stack의 맨위와 한쌍이 아니면 no
                if char == ']' and stack[-1] == '(':
                    no_sts = True
                    break
                # 닫는 괄호와 stack의 맨위와 한쌍이 아니면 no
                elif char == ')' and stack[-1] == '[':
                    no_sts = True
                    break
                # 닫는 괄호와 stack의 맨위와 한쌍이면 yes
                else:
                    stack.pop()
        else:
            continue
    # 닫는 괄호의 예외 처리에 걸렸거나, stack이 안비어 있으면 no
    if no_sts or len(stack) != 0:
        print('no')
    else:
        print('yes')

    



while True:
    string = input()
    if string == '.':
        break
    else:
        solution(string)
Comments