Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.

[2023-08-14] dohyun #110 #122

Merged
merged 1 commit into from
Aug 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions BOJ/괄호의 값/dohyun.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""

풀이시간
- 약 40분

접근법
- 문자열 길이 되게 짧음 -> 시간복잡도 신경쓰지말고 꼼꼼히 구현해보자
- 이전 풀이 문제(쇠 막대기)에서 스택 풀이를 제대로 이해못했지만, 비슷한 느낌인 것 같아 쇠 막대기 풀이 참고
- 올바르지 못한 괄호열은 어떻게 정의할까?
- ( 다음 ] 가 오면 땡
- [ 다음 ) 가 오면 땡
- 소괄호와 대괄호의 개수가 다르면 땡

회고
- 스택 풀이 이해하기!

"""

import sys

text = sys.stdin.readline().strip()
answer = 0
stack = []
tmp_ans = 1 # 곱하기 연산을 해야하므로 1부터 시작

def filter_correct(text):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 예외처리를 정리하셔서 이렇게 filter로 걸어주시는게 너무 좋은 것 같습니다.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

혹시 (8) 이렇게 들어오는 케이스도 필터링이 되나요?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

스택의 유효성을 검증해주는 함수를 따로 정의하신 것 굉장히 좋은 것 같습니다.
다만 cond2에서 count는 O(N)이 소요되는 연산이므로, 모든 스택 연산이 끝났을 때 스택 리스트에 원소가 남아있다면 애초에 개수가 안맞았던 것 아니었을까? 로 접근해보면 어떨까 싶습니다!

cond1 = (text.count('(')==text.count(')')) & (text.count('[')==text.count(']'))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

예외처리도 스터디 때 말씀 드렸던 것처럼 count의 시간복잡도는 O(n)
참고 링크: https://stackoverflow.com/questions/44812468/what-is-the-time-complexity-of-python-lists-count-function

cond2 = (text.count('[)') + text.count('(]') == 0)

return cond1 & cond2

if filter_correct(text):
for i in range(len(text)):
if text[i]=="(":
stack.append("(")
tmp_ans *= 2

elif text[i]=="[":
stack.append("[")
tmp_ans *= 3

elif text[i]==")":
if text[i-1]=="(":
answer += tmp_ans # 괄호연산이 끝났으므로 정답 더해주기
stack.pop()
tmp_ans //= 2 # 소괄호가 닫혔으므로 곱했던 2를 다시 나눠줌

elif text[i]=="]":
if text[i-1]=="[":
answer += tmp_ans # 괄호연산이 끝났으므로 정답 더해주기
stack.pop()
tmp_ans //= 3 # 대괄호가 닫혔으므로 곱했던 3을 다시 나눠줌

else:
answer = 0

print(answer)