문제풀이/백준(Boj) 문제풀이

[백준][스택] 4949. 균형잡힌 세상 (파이썬/Python)

얄루몬 2021. 11. 11. 18:15

<오답>

c1 = c2 = 0

while True:
    s = input()
    if s == ".":
        break
    for i in s:
        if i == '(':
            c1 += 1
        elif i == ')':
            c1 -= 1
        elif i == '[':
            c2 += 1
        elif i == ']':
            c2 -= 1
        if c1 < 0 or c2 <0:
            print("no")
            break

    if c1 == 0 and c2 == 0:
        print("yes")
    elif c1 > 0 and c2 > 0:
        print("no")

 

 

<정답>

while True:
    s = input()
    #종료조건
    if s == '.':
        break
    stack = []
    check = True
    for i in s:
        if i == '(' or i == '[':
            stack.append(i)
        elif i == ')':
            if not stack or stack[-1] == '[':
                check = False
                break
            elif stack[-1] == '(':
                stack.pop()
        elif i == ']':
            if not stack or stack[-1] == '(':
                check = False
                break
            elif stack[-1] == '[':
                stack.pop()
    if check == True and not stack:
        print('yes')
    else:
        print('no')

# len(stack) == 0보다 not stack을 사용해서 빈 리스트인지 확인한다고 한다.