BOJ/백준-4949-python

cosmos·2022년 3월 6일
0
post-thumbnail

문제

풀이

  • 괄호가 짝끼리 매칭되어 닫히면 yes, 아니면 no를 출력해야하는 문제이다.
  • '.'를 기준으로 입력받았다.
  • stack(Last In First Out) 형태로 접근해야지 가장 안쪽에있는 괄호부터 닫게 할 수 있다.
  • 조건문에 맞춰 pop을 하고 괄호가 짝끼리 매칭된다면 stack이 빈 리스트여야 한다. ex) ()(

코드

# https://www.acmicpc.net/problem/4949
# boj, 4949: 균형잡힌 세상, python3

def solve(word):
    stack = []

    for x in word:
        if x == '(' or x == '[':
            stack.append(x)
        elif x == ')':
            if stack:
                bracket = stack.pop()
                if bracket != '(':
                    return 'no'
            else:
                return 'no'
        elif x == ']':
            if stack:
                bracket = stack.pop()
                if bracket != '[':
                    return 'no'
            else:
                return 'no'

    return 'yes' if not stack else 'no'

while True:
    word = str(input().split('.')[0])

    if not word:
        break

    print(solve(word))

결과

출처 & 깃허브

BOJ 4949
GITHUB

0개의 댓글