알고리즘/PROGRAMMERS

개인정보 수집 유효기간(Lv.1)

현대타운301 2024. 3. 19. 00:32

 


 

문제 설명

 

 

 

입출력 예시

 

 

요약

주어진 오늘 날짜와 비교해 유효기간이 만료된 약관의 번호를 담은 int 배열 return

 


 

풀이

 

문제 해석

해당 약관의 개월수를 더해 유효기간을 계산하고 오늘 날짜와 비교해서 지났으면 true 아니면 false

 

 

접근 방식

1) 약관 개월수를 반영한 유효기간 구하기

  → 12보다 큰 경우 year += 1, 약관 개월수 -= 12

  → 약관 개월수 더한 후 해당 날짜의 day -= 1

 

2) 경계값 기준으로 년, 월, 일 세팅

  → month가 12보다 크거나 0인 경우

  → day가 28보다 크거나 0인 경우

 

3) 오늘 날짜와 비교해서 유효한지 판단

  → LocalDateTime 객체 활용

 


 

코드 리뷰

 

import java.util.*;
import java.time.*;	// LocalDateTime을 위한 import

class Solution {
    HashMap<String, Integer> map = new HashMap<>();
    
    public boolean calcDate(String today, String privacy) {	// 유효기간 확인 메소드
        boolean result = false;
        String[] newDate = privacy.split("\\.");	// "." 문자를 기준으로 split할 땐 escape(\\) 처리가 필요
        String[] nowDate = today.split("\\.");
        int priY = Integer.valueOf(newDate[0]);
        int priM = Integer.valueOf(newDate[1]);
        int priD = Integer.valueOf(newDate[2].split(" ")[0]);
        int term = map.get(newDate[2].split(" ")[1]);
        int nowY = Integer.valueOf(nowDate[0]);
        int nowM = Integer.valueOf(nowDate[1]);
        int nowD = Integer.valueOf(nowDate[2]);
        
        while(term > 12) {	// 약관 개월수 계산
            priY++;
            term -= 12;
        }
        priM += term;	// 약관 개월수 더하기
        if(priM > 12) {
            priY++;
            priM -= 12;
        }
        priD -= 1;	// 날짜에서 하루 빼기
        if(priD == 0) {
            priD = 28;
            priM--;
            if(priM == 0) {
                priM = 12;
                priY--;
            }
        }
        LocalDateTime end = LocalDateTime.of(priY, priM, priD, 0, 0, 0);	// yyyy.MM.dd.HH.mm.ss 형식으로 저장
        LocalDateTime now = LocalDateTime.of(nowY, nowM, nowD, 0, 0, 0);
        if(now.isAfter(end)) {	// A.isAfter(B) : A가 B이후라면(end가 now를 지났다면)
            result = true;
        }
        return result;
    }
    public int[] solution(String today, String[] terms, String[] privacies) {
        List<Integer> answerList = new ArrayList<>();
        for(String str : terms) {
            map.put(str.split(" ")[0], Integer.valueOf(str.split(" ")[1]));	// 약관 정보를 key(약관종류)와 value(개월수)로 나누기
        }
        for(int i = 0; i < privacies.length; i++) {
            if(calcDate(today, privacies[i])) {	// 유효기간이 지났는지 확인하는 calcDate 메소드 호출
                answerList.add(i+1);
            }
        }
        int[] answer = new int[answerList.size()];
        for(int i = 0; i < answer.length; i++) {
            answer[i] = answerList.get(i);
        }
        return answer;
    }
}