1662번: 압축

Chaejung·2022년 7월 16일
0

알고리즘_Python

목록 보기
6/22

문제

백준 1662번

파싱과 스택을 적절히 활용하면 크게 문제 없이 풀 수 있을 거라 생각했지만...

첫 번째 시도_메모리초과

str = input()
stack = []

for i in str:
    strLength = 0
    if i==')':
        strIndex=0
        zipNum = ''
        while True:
            temp = stack.pop()
            if temp=='(':
                num = stack.pop()
                strLength += int(num)*len(zipNum)
                stack.append('1'*strLength)
                break
            zipNum += temp
            strIndex+=1
    else:
        stack.append(i)

answer = 0
for i in stack:
    if i == '':
        pass
    else:
        answer += len(i)
print(answer)

깊이가 남다른 코드, 메모리초과가 나올 수 밖에 없다.

참고

성공한 코드

str = input()
stack = []
length = 0
temp = ''

for i in str:
    if i == '(':
        stack.append((temp, length-1))
        length = 0
    elif i == ')':
        zippedNum, preLength = stack.pop()
        length = (int(zippedNum)*length)+preLength
    else:
        length += 1
        temp = i

print(length)

안쪽에 있던 조건문을 앞으로 빼서 정리해서 깊이를 조절했다.
생각해보면, '('가 나온 것부터 쌓는 게 맞는 건데 왜 ')'까지를 잘라낼려고 했는지 모르겠다.

그래서 딱 순서대로 빼니 아주 간결해졌다.

우수 코드

s=[]
f=lambda t:[t,1][type(t)==str]
for i in input():
    if i==')':
        l,t=0,s.pop()
        while t!='(':l+=f(t);t=s.pop()
        s+=[int(s.pop())*l]
    else:s+=[i]
print(sum(map(f,s)))

특이한 구문이 많아서 좀 더 연구해봐야할 것 같아서 기록.

profile
프론트엔드 기술 학습 및 공유를 활발하게 하기 위해 노력합니다.

0개의 댓글

관련 채용 정보