1. 첫 번째 코드 (정답 코드)
#괄호 균형 판단 프로그램
#(), []
while(True):
tf=0
line = input()
small=0#괄호가 열리면 +1, 닫히면 -1
large=0
#<괄호의 균형을 맞춰야하는 문제 해결 방법>
#문이 열릴 때마다,색을 칠해준다.
#닫을 때 칠해진 색과 닫을 색이 일치하지 않으면 break
#일치하면 그 색을 뽑아버린다.
color=[]
if len(line)==1 and line[-1]=='.':#.이 들어오면 정지
break
else:
for i in line:
if i == '(':
small+=1
color.append('small')
elif i==')':
small-=1
if small <0: #한 번이라도 이런 경우가 생기면 에러처리를 위해 tf=-1로 변경.
tf=-1
break
if color[-1] !='small':
tf=-1
break
else:
color.pop()
elif i=='[':
large+=1
color.append('large')
elif i==']':
large-=1
if large <0:
tf=-1
break
if color[-1] !='large':
tf=-1
break
else:
color.pop()
if small == 0 and large == 0 and tf==0:
print('yes')
else:
print('no')
#마지막에 .을 넣어도 끝나지 않음
#=> while문 안의 for문이 아니라, for문 시작 전에 if break문을 넣어줬음.
2. 정리한 코드(정답 코드)
위의 코드가 조금 지저분한 것 같아서 정리 필요.
while(True):
tf=0 #오답이 확정일 때 -1로 구분지어주는 역할.
line = input() #입력 받기
#<괄호의 균형을 맞춰야하는 문제 해결 방법>
#가장 최근에 열린 괄호가, 자신의 짝과 일치하는지 확인한다.
#일치하지 않으면 break
#일치하면 그 색을 뽑아버린다.
stack=[]
if len(line)==1 and line[-1]=='.':#.이 들어오면 정지
break
else:
for i in line:
if i == '(' or i=='[':
stack.append(i)
elif i==')':
if len(stack)==0 or stack[-1] !='(':
tf=-1
break
else:
stack.pop()
elif i==']':
if len(stack)==0 or stack[-1] !='[':
tf=-1
break
else:
stack.pop()
if len(stack)==0 and tf!=-1:
print('yes')
else:
print('no')
3. 최종 코드 : import sys 입력만 더 효율적으로
import sys
input=sys.stdin.readline
#readline은 공백도 받으므로, rstrip()로 공백 제거.
while(True):
tf=0 #오답이 확정일 때 -1로 구분지어주는 역할.
line = input().rstrip() #입력 받기
#<괄호의 균형을 맞춰야하는 문제 해결 방법>
#가장 최근에 열린 괄호가, 자신의 짝과 일치하는지 확인한다.
#일치하지 않으면 break
#일치하면 그 색을 뽑아버린다.
stack=[]
if len(line)==1 and line[-1]=='.':#.이 들어오면 정지
break
else:
for i in line:
if i == '(' or i=='[':
stack.append(i)
elif i==')':
if len(stack)==0 or stack[-1] !='(':
tf=-1
break
else:
stack.pop()
elif i==']':
if len(stack)==0 or stack[-1] !='[':
tf=-1
break
else:
stack.pop()
if len(stack)==0 and tf!=-1:
print('yes')
else:
print('no')
이때 readline은 공백도 받으므로, rstrip()로 공백을 제거해줘야한다.
'코딩테스트 준비 > Python' 카테고리의 다른 글
백준 1654 랜선 자르기 코드 및 설명 (0) | 2023.09.01 |
---|---|
백준 15829 python Hashing 문제 풀이 (0) | 2023.08.29 |
백준 python 1929 소수 구하기 : 시간초과 그리고 해결 (0) | 2023.08.20 |
백준 2775 python : 부녀회장이 될테야 (0) | 2023.08.20 |
1676 python 팩토리얼 0의 개수 4가지 풀이법 (0) | 2023.08.16 |