코딩테스트/구현|기타

[큐] 프로그래머스 [1차] 캐시 C++

유(YOO) 2023. 1. 20. 22:36
#include <string>
#include <vector>
#include <queue>

using namespace std;

string toLower(string str) {
    for (int i = 0; i < str.size(); i++) {
        str[i] = tolower(str[i]);
    }
    return str;
}

int solution(int cacheSize, vector<string> cities) {
    int answer = 0;
    queue<string> q;
    for (auto i : cities) {
        bool isFind = false;
        int range = cacheSize > q.size() ? q.size() : cacheSize;
        for (int j = 0; j < range; j++) {
            if (q.empty()) break;
            if (q.front() == toLower(i)) {
                answer++;
                isFind = true;
            }
            else q.push(q.front());
            q.pop();
        }
        if (!q.empty() && (q.size() == cacheSize)) q.pop();
        if (!isFind) answer += 5;
        q.push(toLower(i));
    }
    return answer;
}

* 참고

잘못된 풀이

// 실패
#include <string>
#include <vector>
#include <queue>

using namespace std;

string toLower(string str) {
    for (int i = 0; i < str.size(); i++) {
        str[i] = tolower(str[i]);
    }
    return str;
}

int solution(int cacheSize, vector<string> cities) {
    int answer = 0;
    queue<string> q;
    for(auto i : cities) {
        bool isFind = false;
        for(int j=0; j<cacheSize; j++) {
            if(q.empty()) break;
            if(j == q.size()) break; // 중간에 큐 사이즈 변함
            if(q.front() == toLower(i)) {
                answer++;
                isFind = true;
            }
            else q.push(q.front());
            q.pop();
        }
        if(!q.empty() && (q.size() == cacheSize)) q.pop();
        q.push(toLower(i));
        if(!isFind) answer+=5;
    }
    return answer;
}