[Algorithm] [백준] 4949 균형잡힌 세상

myeonji·2022년 2월 20일
0

Algorithm

목록 보기
49/89
while True:
    s = []
    lst = sys.stdin.readline().rstrip()
    if lst == '.':  # 마지막 문장
        break
    else:
        for i in range(len(lst)):
            if lst[i] == '(' or lst[i] == '[':
                s.append(lst[i])
            elif lst[i] == ')':
                if len(s) != 0:
                    if s.pop() == '(':
                        continue
                    else:
                        print('no')
                        break
            elif lst[i] == ']':
                if len(s) != 0:
                    if s.pop() == '[':
                        continue
                    else:
                        print('no')
                        break
        else:
            if len(s) == 0:
                print('yes')
            else:
                print('no')

조건문을 명확하게 걸지 않아서 에러났다.

')' 하고 ']' 조건문에서 pop을 할 때, else문에서는 pop을 하면 안되는데 if문에서 pop하고 조건 성립 안 하면 else로 간다. 이때도 pop이 이미 된 상태라 에러가 난 것이다.

<다시 풀기>

import sys

while True:
    s = []
    temp = True
    lst = sys.stdin.readline().rstrip()
    if lst == '.':  # 마지막 문장
        break

    for i in range(len(lst)):
        if lst[i] == '(' or lst[i] == '[':
            s.append(lst[i])

        elif lst[i] == ')':
            if not s or s[-1] == '[':
                temp = False
                break
            elif s[-1] == '(':
                s.pop()

        elif lst[i] == ']':
            if not s or s[-1] == '(':
                temp = False
                break
            elif s[-1] == '[':
                s.pop()

    if temp == True and not s:  # 비워져있으면
        print('yes')
    else:
        print('no')

성공성공

0개의 댓글