Algorithm/BOJ
[BOJ] 4949 균형잡힌 세상
SolB
2022. 5. 28. 23:25
class 2


while True:
br = input()
if br == '.':
break
stack = []
chk = True
for i in br:
if i == '(' or i == '[':
stack.append(i)
elif i == ')':
if not stack or stack[-1] == '[':
chk = False
break
elif stack[-1] == '(':
stack.pop()
elif i == ']':
if not stack or stack[-1] == '(':
chk = False
break
elif stack[-1] == '[':
stack.pop()
if chk == True and not stack:
print('yes')
else:
print('no')
<코드 설명>
while문으로 무한반복을 시켜주고 입력받은 문자가 '.'일 때 break하도록 하였다.
입력받은 br을 하나씩 검사해준다.
-> br이 '(', '['이면 stack에 추가해준다. br이 ')'이면 stack이 없거나 stack에 마지막'['일 때 짝이 맞지 않기 때문에 chk를 False로 변경해준다. stack의 마지막이 '('이였다면 짝이 맞으므로 pop해준다.
-> br이 ']'이면 stack이 없거나 stack에 마지막'('일 때 짝이 맞지 않기 때문에 chk를 False로 변경해준다. stack의 마지막이 '['이였다면 짝이 맞으므로 pop해준다.
결론적으로 chk이 True였으며 stack이 모두 pop된 상태라면 yes를 출력해주고, 그렇지 않으면 no를 출력해주었다.
<실행 결과>

