import sys
while True:
stack = []
line = sys.stdin.readline().rstrip()
if line =='.':
break
for word in line:
if word == '.':
break
if word == '(' or word == '[' :
stack.append(word)
elif word ==')':
if stack:
if stack[-1] == '(':
stack.pop()
else:
stack.append(word)
break
else:
stack.append(word)
break
elif word ==']':
if stack:
if stack[-1] == '[':
stack.pop()
else:
stack.append(word)
break
else:
stack.append(word)
break
if not stack:
print("yes")
else:
print("no")
한줄을 받고 한글자씩 잘라서 if 문으로 확인하는 코드
=> 중복 구문이 많고, 코드가 더럽다.
import sys
def is_balanced(line):
stack = []
for char in line:
if char in '([':
stack.append(char)
elif char in ')]':
if not stack or '(['.index(stack.pop()) != ')]'.index(char):
return False
return not stack
while True:
line = sys.stdin.readline().rstrip()
if line == '.':
break
if is_balanced(line):
print("yes")
else:
print("no")
in 구문을 이용해 한꺼번에 ( , [ 를 확인한다.
if not stack으로 stack이 비어있으면 우선 걸러주고
index(stack.pop) 함수를 이용해 기존 if문 두번 사용한걸 한번으로 줄였다.