chyam

[프로그래머스 Lv2,python]- 롤케이크 자르기 본문

프로그래머스/LV2

[프로그래머스 Lv2,python]- 롤케이크 자르기

chyam_eun 2025. 1. 16. 11:07

https://school.programmers.co.kr/learn/courses/30/lessons/132265

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

def solution(topping):
    cnt = 0
    n=1
    while(n<len(topping)):
        set_1=list(set(topping[:n])) # n번째까지 잘라서 중복 제거하기
        set_2=list(set(topping[n:]))
        if len(set_1)==len(set_2): # 길이 같으면 cnt증가
            cnt+=1
        n+=1
    return cnt
    
def solution(topping): # 얜 딕셔너리로 구현한거
    from collections import Counter
    cnt = 0
    n=1
    while(n<len(topping)):
        top1=Counter(topping[:n])
        top2=Counter(topping[n:])
        if len(top1)==len(top2):
            cnt+=1
        n+=1
    return cnt

 

위의 두 풀이는 시간초과가 걸린풀이이다.

아래는 통과한 풀이로 딕셔너리를 사용했다. 다른분 풀이를 보고 동생이 먹을거를 집합으로 표현하면 더 간단하게 할 수 있다는걸 알게되었다.

from collections import Counter

def solution(topping):
    cnt=0
    me=Counter(topping) # 내가 먹을거
    bro={} # 동생이 먹을거
    for top in topping:
        me[top]-=1 # 동생이 먹어서 줄어든다
        if top not in bro: # 없는거면 추가해주고 있으면 1더해주기
            bro[top]=1
        else:
            bro[top]+=1
        if me[top]==0: # 내가먹을게 없으면 그 키를 지워주기
            del me[top]
        if len(me)==len(bro): # 종류 같으면 증가
            cnt+=1
        elif len(me)<len(bro): # 동생이 더 많은 종류 가져가면 종료
            break
    return cnt