관리 메뉴

Mini

프로그래머스 캐시 Python cpp //LRU구현 ,tolower 본문

Algorithm/programmers

프로그래머스 캐시 Python cpp //LRU구현 ,tolower

Mini_96 2023. 7. 11. 22:50

코딩테스트 연습 - [1차] 캐시 | 프로그래머스 스쿨 (programmers.co.kr)

 

프로그래머스

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

programmers.co.kr

* Python 

- idea

 list의[0]을 아웃대상으로 본다.

ex) [0] [1] [2]

jeju pangyo seoul

판교가들어오면 -> pop(1), append(판교) -> 맨뒤로보내서 아웃안되도록

 

 

1. all 소문자로

 

2.q안에 이미존재 :  answer+1

-> 제일뒤로보내 =>아웃되지않도록

q.pop(q.index(city))   //list.index(해당값)

q.append(city)

3. 존재하지않는경우 :   answer+5

최대값미만 -> append

최대값이상 -> pop(0), append

def solution(cacheSize, cities):
    answer = 0
    if(cacheSize==0):
        return 5*len(cities)
    
    q=[]
    
    for city in cities:
        city=city.lower()
        #print(q)
        if city in q:
            answer+=1
            q.pop(q.index(city))
            q.append(city)

        else:
            answer+=5
            if(len(q)<cacheSize):
                q.append(city)
            else:
                q.pop(0)
                q.append(city)

    
    return answer

 

* cpp

- python의 in 구현 && list.index(값) 구현

int checkIn(string city){
    for(int i=0;i<v.size();++i){
        if(v[i]==city){
            return i;
        }
    }
    
    return -1;
}

- tolower는 문자별로 각각해야함

for(int i=0;i<city.size();++i){
            city[i]=tolower(city[i]);
        }

 

- pop(index) py == v.erase(v.begin()+index)) cpp

v.erase(v.begin()+idx);

 

#include <bits/stdc++.h>

using namespace std;

vector<string> v;
int checkIn(string city){
    for(int i=0;i<v.size();++i){
        if(v[i]==city){
            return i;
        }
    }
    
    return -1;
}
int solution(int cacheSize, vector<string> cities) {
    int answer = 0;
    
    if(cacheSize==0) return 5*cities.size();
    
    for(auto city : cities){
        //1. all 소문자로
        for(int i=0;i<city.size();++i){
            city[i]=tolower(city[i]);
        }
        //cout<<city<<endl;
        /*for(auto s : v){
            cout<<s<<" ";
        }
        cout<<endl;*/
        
        /*2.q안에 이미존재 :  answer+1

        -> 제일뒤로보내 =>아웃되지않도록

        q.pop(q.index(city))   //list.index(해당값)

        q.append(city)*/
        int idx=0;
        if((idx=checkIn(city))>=0){
            answer+=1;
            v.erase(v.begin()+idx);
            v.push_back(city);
        }
            
            
        
        /*3. 존재하지않는경우 :   answer+5

        최대값미만 -> append

        최대값이상 -> pop(0)*/
        else {
            answer+=5;
            if(v.size()<cacheSize){
                v.push_back(city);
            }
            else{
                v.erase(v.begin());
                v.push_back(city);
            }
        }
        
        
    }

    

    return answer;
}