코딩테스트/프로그래머스

[프로그래머스] 캐시 (Lv.2)

34suuuuu 2025. 3. 28. 09:42

✴️ 문제

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

 

✴️ 문제 풀이

 

주의해야하는 점은

1. cacheSize가 0인 경우

2. NewYork과 newyork를 같이 입력을 준 경우

 

1번의 경우에는 계속해서 miss만 처리해주면 되는 경우이기 때문에

cities 배열의 길이 * 5 를 return해줬다.

if(cacheSize == 0){
	return cities.length * 5;
}

 

2번의 경우에는 대소문자를 구분하지 않는 의미이므로

모두 대문자나 소문자로 통일하고 처리해주면 된다.

나같은 경우에는 모두 대문자로 통일해줬다

s = s.toUpperCase();

 

 

문제 풀이 과정을 생각해보면 아래와 같다

  1. cache에 이미 존재한다면
    • 해당 값을 삭제하고 맨 뒤에 다시 추가함으로써 맨 뒤로 이동
    • answer += 1
  2. cache에 존재하지 않는다면? 
    • cache배열의 길이와 cacheSize가 같다면?
      • 맨앞에 존재하던 값을 빼기
    • 새로운 값으 맨 뒤에 추가
    • answer += 5;

 

 

✴️ 전체 코드 (Java)

import java.util.*;

class Solution {
    public int solution(int cacheSize, String[] cities) {
        int answer = 0;
        LinkedList<String> cache= new LinkedList<>();
        
        if(cacheSize == 0){
            return cities.length * 5;
        }
        
        for(String city : cities){ 
            city = city.toUpperCase();
            
            if(cache.contains(city)){
                cache.remove(city);
                cache.add(city);
                answer++;
            }else{
                if(cache.size() == cacheSize){
                    cache.remove(0);
                }
                cache.add(city);
                answer+=5;
            }
        }
        return answer;
    }
}