알고리즘/프로그래머스 1단계

프로그래머스 - 개인정보 수집 유효기간 - C++

게임만드는학생 2024. 7. 22. 15:22

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

 

프로그래머스

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

programmers.co.kr

 

#include <string>
#include <vector>
#include <map>
using namespace std;

vector<int> solution(string today, vector<string> terms, vector<string> privacies) {
    vector<int> answer;
    map<char,int> m;
    int year = stoi(today.substr(0,4));
    int month = stoi(today.substr(5,2));
    int day = stoi(today.substr(8));
    
    for(int i=0;i<terms.size();i++)
    {
        m.insert({terms[i][0],stoi(terms[i].substr(2))});
    }
    
    for(int i=0;i<privacies.size();i++)
    {
        // 수집한 날짜
        int my = stoi(privacies[i].substr(0,4));
        int mm = stoi(privacies[i].substr(5,2));
        int md = stoi(privacies[i].substr(8,2));
        
        char type = privacies[i][11];
        
        // 유효기간
        int ty = my;
        int tm = mm + m[type];
        int td = md;
        td--;
        if(td<=0)
        {
            td=28;
            tm--;
            if(tm<=0)
            {
                tm=12;
                ty--;
            }
        }
        
        while(tm>12)
        {
            tm-=12;
            ty++;
        }
        
        if(year>ty)answer.push_back(i+1);
        else if(year==ty)
        {
            if(month>tm)answer.push_back(i+1);
            else if(month==tm)
            {
                if(day>td)answer.push_back(i+1);
            }
            
        }
    }
    
    return answer;
}

 

개인정보가 약관에 따라 유효기간이 존재하는데 오늘 날짜로 그 유효기간이 지났는지 판단하는 문제이다. 

 

오늘날짜, 약관의 종류와 그에따른 유효기간, 수집된 개인정보 목록이 주어진다. 

약관의 종류는 map을 통해서 <종류, 유효기간> 으로 저장하였다. 

 

오늘 날짜와 수집된 개인정보의 약관종류는 형식이 정해져있기 때문에  substr함수로 나눴다. 

 

for문을 돌며 privacies[i] 의 수집된 날짜, 약관 종류에 따른 유효기간을 먼저 구한다. 

td--;
        if(td<=0)
        {
            td=28;
            tm--;
            if(tm<=0)
            {
                tm=12;
                ty--;
            }
        }

만약 2월 3일수집한 정보는 3달 유효기간이라 했을 때, 5월 2일까지이기 때문에 

day에 -1을 해야한다. 

 

if(year>ty)answer.push_back(i+1);
        else if(year==ty)
        {
            if(month>tm)answer.push_back(i+1);
            else if(month==tm)
            {
                if(day>td)answer.push_back(i+1);
            }
            
        }

기간이 넘었는지 판단하기 위해 연도부터 비교하고 

연도가 넘지 않았다면 더 볼필요가 없다.

같다면 month, day 순으로 같은 방법으로 비교한다.