백준 4949: 균형잡힌 세상 (파이썬)
4949번: 균형잡힌 세상
하나 또는 여러줄에 걸쳐서 문자열이 주어진다. 각 문자열은 영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어져 있으며, 길이는 100글자보다 작거나 같다. 각 줄은 마침표(".")로 끝난다
www.acmicpc.net
# [BOJ] 4949. 균형잡힌 세상
OP = ['(', '[']
CP = [')', ']']
while 1:
S = input()
if S == '.':
break
# 괄호가 아예 없는 경우 yes 처리
if '(' not in S and ')' not in S and '[' not in S and ']' not in S:
print('yes')
# 여기서부터 문제풀이
else:
ans = 'yes'
stack = []
for s in S:
if s in OP: # 여는 괄호일 경우 stack에 push
stack.append(s)
elif s in CP: # 닫는 괄호일 경우
if len(stack) == 0:
ans = 'no'
elif s == ')' and stack[-1] != '(':
ans = 'no'
elif s == ')' and stack[-1] == '(':
stack.pop(-1)
elif s == ']' and stack[-1] != '[':
ans = 'no'
elif s == ']' and stack[-1] == '[':
stack.pop(-1)
# 처리가 끝나도 아직 열린 괄호가 남아있는 경우
if len(stack) > 0:
ans = 'no'
print(ans)
'Algorithm > BOJ' 카테고리의 다른 글
[BOJ] 2805 나무 자르기 (python) (0) | 2022.12.12 |
---|---|
[BOJ] 1966 프린터 큐 (python) (0) | 2022.12.11 |
[BOJ] 2217 로프 (python) (0) | 2022.11.27 |
[BOJ] 10989 수 정렬하기 3 (python) (0) | 2022.10.03 |
[BOJ] 11652 카드 (python) (0) | 2022.10.01 |