<프로그래머스 C++> 개인정보 수집 유효기간 풀이

2026. 6. 1. 12:04Programmers

문제

개인정보는 약관에 따라 유효기간이 정해져 있다.

오늘 날짜를 기준으로 유효기간이 지난 개인정보 번호를 오름차순으로 return하는 문제이다.

 

모든 달은 28일 까지만 있다고 가정한다.


문제 해결 과정

1. 날짜를 총 일수로 변환

날짜 비교를 편하게 하기 위해 YYYY.MM.DD 문자열을 총 일수로 변환해서 비교했다.

모든 달이 28일이므로

총 일수 = 년 * 12 * 28 + 월 * 28 + 일

 

2. 약관 유효기간 저장

약관 종류(char)를 키로, 유효히간(int)을 값으로 map<char,int>에 저장한다.

 

3. 파기 조건

수집 날짜 + 유효기간(달 * 28) <= 오늘 날짜의 조건이 성립하면 파기하고 answer += i + 1을 해서 결과에 추가한다.


문제 풀이

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

int toDate(string date) {
    int y = stoi(date.substr(0, 4));
    int m = stoi(date.substr(5, 2));
    int d = stoi(date.substr(8, 2));
    return y * 12 * 28 + m * 28 + d;
}

vector<int> solution(string today, vector<string> terms, vector<string> privacies) {
    vector<int> answer;
    int todayDate = toDate(today);
    map<char, int> termDate;

    for(auto& it : terms)
    {
        char type = it[0];
        int month = stoi(it.substr(2));
        termDate[type] = month;
    }

    for(int i = 0; i < privacies.size(); ++i)
    {
        int date = toDate(privacies[i].substr(0, 10));
        char type = privacies[i][11];
        int plus = termDate[type] * 28;

        if(date + plus <= todayDate)
            answer.push_back(i + 1);
    }

    return answer;
}

풀이 핵심

1. 날짜 변환 함수

int toDate(string date) {
    int y = stoi(date.substr(0, 4));
    int m = stoi(date.substr(5, 2));
    int d = stoi(date.substr(8, 2));
    return y * 12 * 28 + m * 28 + d;
}

YYYY.MM.DD 형태의 문자열을 substr로 파싱해서 총 일수로 변환한다.

총 일수로 변환하면 날짜 비교를 단순한 정수 비교로 처리할 수 있어 직관성있게 비교할 수 있다.

 

2. 약관 파싱

for(auto& it : terms)
{
    char type = it[0];
    int month = stoi(it.substr(2));
    termDate[type] = month;
}

"A 6" 형태에서 첫 글자가 약관 종류, 인덱스 2부터가 유효기간이다. 

map<char, int>에 저장해 약관 종류로 빠르게 유효기간을 조회할 수 있다.

 

3. 파기 대상 판별

int date = toDate(privacies[i].substr(0, 10));
char type = privacies[i][11];
int plus = termDate[type] * 28;

if(date + plus <= todayDate)
    answer.push_back(i + 1);

privacies[i]는 "2021.05.02 A" 형태이다. 앞 10글자가 날짜, 인덱스 11번째가 약관의 종류이다. 

수집 날짜 + 유효기간이 오늘 날짜 이하면 파기 대상이다. 개인정보는 1부터 시작하므로 i+1로 추가한다.


트러블 슈팅

 char type = privacies[i].substr(11) 타입 오류

char type = privacies[i].substr(11);

substr은 string을 반환하는데 char에 넣으려 해서 컴파일 오류가 발생했다.

 

오류리스트를 살펴보고 확인해본 결과, 한 글자만 필요하므로 인덱스로 접근해야 한다.

 

수정한 코드는 다음과 같다.

char type = privacies[i][11];

핵심 포인트

1. 날짜를 총 일수로 변환해서 비교하면 직관성있고 단순해진다.

 

2. 약관 유효기간은 map<char, int>로 저장해서 시간복잡도 O(1)로 조회해서 성능을 올린다.