728x90
Overview
- 체감 난이도: ★★☆☆☆ # 어려운 문제는 아닌데, 처음 생각했던 방법의 해결책을 찾지 못해 어려움을 느낌
- 문제 레벨: 실버 4
- 문제 유형: 스택
- 풀이 상태: 답안참고 / 스스로 해결
- 추후: 다시 풀어보기 / 간단 복습 / 완벽 이해
[문제]
https://www.acmicpc.net/problem/4949
[코드]
while True:
s = input().strip('\n')
if s == '.':
break
st, chk = [], True
for i in s:
if i == '(' or i == '[':
st.append(i)
elif i == ')':
if len(st) == 0 or st[-1] != '(':
chk = False
else:
st.pop()
elif i == ']':
if len(st) == 0 or st[-1] != '[':
chk = False
else:
st.pop()
if chk and not st:
print("yes")
else:
print("no")
[리뷰]
위의 코드를 완성하기까지 시행착오가 많았는데,
1. 출력 yes, no 를 대문자로 출력했다.
2. 입력의 종료조건을 제대로 인지하지 않았다. -> try, except EOFerror 문까지 작성했었음
3. ), ] 닫는 괄호가 먼저 입력되는 경우를 생각하지 않았다.
틀린 코드
더보기
3번을 구현하지 않아 틀린 코드
while True:
s = input().strip('\n')
if s == '.':
break
st, chk = [], True
for i in s:
if i == '(' or i == '[':
st.append(i)
elif len(st) != 0 and (i == ')' or i == ']'):
if (i == ')' and st[-1] == '(') or (i == ']' and st[-1] == '['):
st.pop()
else:
chk = False
break
if chk and not st:
print("yes")
else:
print("no")
3번의 경우를 추가한 코드
while True:
s = input().strip('\n')
if s == '.':
break
st, chk = [], True
for i in s:
if i == '(' or i == '[':
st.append(i)
elif i == ')' or i == ']':
if not st:
chk = False
break
elif (i == ')' and st[-1] == '(') or (i == ']' and st[-1] == '['):
st.pop()
else:
chk = False
break
if chk and not st:
print("yes")
else:
print("no")
하지만 여전히 틀렸다고 뜬다. 이렇게 경우를 나누면 안 되는 경우가 있나보다.
추후 방법을 알게 된다면 내용을 추가하겠다.
반응형
'🚩 Coding Test > Baekjoon' 카테고리의 다른 글
[BOJ][Python] 10816 숫자 카드 2 (0) | 2024.08.18 |
---|---|
[BOJ][Python] 2504 괄호의 값 (0) | 2024.08.15 |
[BOJ][Python] 9461 파도반 수열 (0) | 2024.07.31 |
[BOJ][Python] 4375 1 (0) | 2024.07.25 |
[BOJ][Python] 1629 곱셈 (0) | 2024.07.25 |