BOJ-Algorithm
백준 4949 - 균형잡힌 세상
bellhundred
2022. 1. 4. 00:30
https://www.acmicpc.net/problem/4949
4949번: 균형잡힌 세상
하나 또는 여러줄에 걸쳐서 문자열이 주어진다. 각 문자열은 영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어져 있으며, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마
www.acmicpc.net
ans = []
while True:
text = input()
if text=='.':
break
stack = []
flag = "yes"
for word in text:
if word=='(' or word=='[':
stack.append(word)
elif word==')':
if not stack:
flag="no"
break
if stack[-1]=='(':
stack.pop(-1)
else:
flag="no"
break
elif word==']':
if not stack:
flag="no"
break
elif stack[-1]=='[':
stack.pop(-1)
else:
flag="no"
break
elif word=='.':
break
if stack:
flag="no"
ans.append(flag)
for word in ans:
print(word)
이전의 괄호 문제의 업그레이드 버전이다.
괄호가 하나 추가된 것 말고는 별 차이는 없다.
여전히 체크해야 하는건
-')' 나 ']'가 입력되었을 때
1. stack에 값이 있는지 체크
2. stack[-1]이 적절한 괄호인지 체크
- 반복문이 끝났을 때
1. stack에 값이 있는지 체크
하는 것이 중요하다.