Study/Coding Test

[2018 1차 KAKAO] 캐시

_gayeon 2021. 10. 8. 16:58

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

 

코딩테스트 연습 - [1차] 캐시

3 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "Jeju", "Pangyo", "Seoul", "NewYork", "LA"] 50 3 ["Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul"] 21 2 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "SanFrancisco", "Seoul", "Ro

programmers.co.kr

 

 

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cctype>

using namespace std;

int solution(int cacheSize, vector<string> cities) {
    int answer = 0;
    vector<string> cache(cacheSize);
    
    if(cache.size() == 0){
        return cities.size()*5;
    }
    
    for(int i=0; i<cities.size(); i++){
        string lowerCities = " ";
        for(int j=0; j<cities[i].size(); j++){
            lowerCities += tolower(cities[i][j]);
        }
        
        auto iter = find(cache.begin(), cache.end(), lowerCities);
        if(iter != cache.end()){ //찾았을때
            cache.erase(iter);
            cache.push_back(lowerCities);
            answer+=1;
        }
        else{
            if(cacheSize>0 && cache.size() == cacheSize){
                cache.erase(cache.begin());
            }
            cache.push_back(lowerCities);
            answer+=5;
        }
    }
    
    return answer;
}

구현하기에는 어렵지 않았지만, 반례를 찾기 힘들었다.

cacheSize가 0이고 cities가 ["LA", "LA"]인 경우에 10이 나와야하는데 6이 나오는 부분을 해결하니 통과되었다.