Python/Programmers

[프로그래머스/Python] Lv 2. 롤케이크 자르기

hwangzzi 2023. 5. 1. 06:58

 

⭐ 문제 링크

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

⭐ 풀이 코드

 시간초과

def solution(topping):
    answer = 0
    
    for i in range(len(topping)):
        a = set(topping[:i])
        b = set(topping[i:])
            
        if len(a) == len(b):
            answer += 1
    
    return answer

리스트 슬라이싱을 사용했더니 시간초과가 발생했다!..

 

 

 통과

from collections import Counter

def solution(topping):
    answer = 0
    
    topping_c = Counter(topping)  # topping 원소 개수
    topping_s = set()  # topping 개수 비교를 위한 새로운 집합
    
    for t in topping:
        topping_s.add(t)
        topping_c[t] -= 1
        if topping_c[t] == 0:
            topping_c.pop(t)
        if len(topping_c) == len(topping_s):
            answer += 1
    
    return answer

다른 사람 풀이 참고해서 Counter를 사용했다.


  1. topping_c와 topping_s를 정의
  2. topping 원소를 반복하면서 topping_s에 원소 추가, topping_c의 원소 value값 1씩 빼주기
  3. topping_c에 더 이상 원소가 없을 경우, 원소 제거
  4. topping_c와 topping_s의 원소 개수가 같을 경우, 카운트