본문 바로가기
알고리즘/프로그래머스

알고리즘(C++) / 프로그래머스 level 2 : 캐시

by clean_h 2021. 7. 13.
728x90

level 2 : 캐시

https://programmers.co.kr/learn/courses/30/lessons/17680?language=cpp 

 

코딩테스트 연습 - [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 <iostream>
#include <string>
#include <vector>
#include <algorithm> //remove 헤더

using namespace std;

int solution(int cacheSize, vector<string> cities) {
    int answer = 0;
    vector<string> cache;
    if (cacheSize == 0)
        return cities.size() * 5;

    for (int i = 0; i < cities.size(); i++) {
        transform(cities[i].begin(), cities[i].end(), cities[i].begin(), ::tolower); //소문자 변환

        auto it = find(cache.begin(), cache.end(), cities[i]);
        if (it == cache.end()) {
            if (cache.size() == cacheSize) {
                cache.erase(remove(cache.begin(), cache.end(), cache[0]), cache.end()); //제일 앞 캐시 제거
            }
            answer += 5;
        }
        else {
            cache.erase(remove(cache.begin(), cache.end(), cities[i]), cache.end()); //제거
            answer++;
        }

        cache.push_back(cities[i]);
    }
    return answer;
}

int main() {
    int cacheSize = 3;
    vector<string> cities = { "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul" };
    cout << solution(cacheSize, cities) << "\n";
    return 0;
}

 

고찰

문제를 해결하기 위해 queue, list, map, vector 등 어떤 stl 사용할지 고민이 되었다. erase함수와 find함수를 사용하기에 vector가 가장 적합할것 같아서 vector를 사용하였다. 

 

대소문자 변환하는 방법

transform(cities[i].begin(), cities[i].end(), cities[i].begin(), ::tolower); //소문자 변환
transform(cities[i].begin(), cities[i].end(), cities[i].begin(), ::toupper); //대문자 변환

다음과 같이 대소문자 변환을 해줄 수 있다.

 

 

처음 채점한 결과 7번, 17번 틀렸는데 그 이유는 size가 0일 때를 처리해주지 않아서 틀렸었다.

728x90

댓글