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():
q.append(g)
else :
if exp[q[-1]] == g:
q.pop()
else:
answer = 0
break
print('#{} {}'.format(tc, answer))