[SWEA] 1218. [S/W 문제해결 기본] 4일차 - 괄호 짝짓기

야금야금 공부·2023년 4월 29일
0

SWEA

목록 보기
10/43
post-thumbnail

1218. [S/W 문제해결 기본] 4일차 - 괄호 짝짓기


문제 풀이

import sys
sys.stdin = open("input.txt", "r")

for t in range(1, 11):

    n = int(input())
    arr = list(input())

    stack = []
    ans = 1

    for i in arr:
        if i == '(':
            stack.append(i)

        elif i == ')' and len(stack):
            if '(' not in stack:
                ans = 0
            else:
                stack.pop(stack.index('('))


        if i == '<':
            stack.append(i)
        elif i == '>' and len(stack):
            if '<' not in stack:
                ans = 0
            else:
                stack.pop(stack.index('<'))

        if i == '[':
            stack.append(i)
        elif i == ']' and len(stack):
            if '[' not in stack:
                ans = 0
            else:
                stack.pop(stack.index('['))

        if i == '{':
            stack.append(i)
        elif i == '}' and len(stack):
            if '{' not in stack:
                ans = 0
            else:
                stack.pop(stack.index('{'))

    print(f"#{t} {ans}")

다른 정답 코드

  • if-else 문으로 구현하였는데, 딕셔너리를 활용한 깔끔한 코드를 보았다.
from collections import deque

exp = {'[':']', '{':'}', '(':')', '<':'>'}

for tc in range(1, 11):

    answer = 1
    _ = int(input())
    
    q = deque()
    gwal = input()            # 입력 받은 문자열
    
    for g in gwal:
        if g in exp.keys():   # key 값이라면, q에 넣음
            q.append(g)
            
        else :                    # key 값이 아니라면
            if exp[q[-1]] == g:   # 문자 g가 key q[-1]의 value와 같다면, pop()
                q.pop()
                
            else:                 # g가 q의 마지막 값이 아니라면, 유효하지 않음
                answer = 0
                break

    print('#{} {}'.format(tc, answer))

0개의 댓글