[JAVA] 개인정보 수집 유효기간
< 풀이 >
import java.util.*;
class Solution {
//유효기간이 지났는지 확인해주는 함수 (false=> 유효기간 지남! )
static boolean check(String today,int year,int month,int day){
String td[]=today.split("\\.");
int td_year=Integer.parseInt(td[0]);
int td_month=Integer.parseInt(td[1]);
int td_day=Integer.parseInt(td[2]);
if(td_year>year)
return false;
else if(td_year==year){
if(td_month<month)
return true;
else if(td_month==month){
if(td_day<=day)
return true;
else
return false;
}
else
return false;
}
else
return true;
}
public ArrayList solution(String today, String[] terms, String[] privacies) {
ArrayList<Integer> answer = new ArrayList<>();
HashMap<String,Integer> map=new HashMap<>();
for(int i=0;i<terms.length;i++){
String term[]=terms[i].split(" ");
map.put(term[0],Integer.parseInt(term[1])); // map에 약관 별 유효기간 저장
}
for(int i=0;i<privacies.length;i++){
String privacy[]=privacies[i].split(" ");
String date[]=privacy[0].split("\\.");
int year=Integer.parseInt(date[0]); //년
int month=Integer.parseInt(date[1]); //월
int day=Integer.parseInt(date[2]); //일
int expiration=map.get(privacy[1]); //약관 종류에 따른 유효기간 가져오기
month+=expiration;
if (month > 12) {
year += (month/12);
month%=12;
if(month==0){
year--;
month=12;
}
}
if(day==1){
day=28;
month--;
}
else {
day--;
}
boolean ok=check(today,year,month,day); // 유효기간이 지났는지 안지났는지 확인
if(!ok)
answer.add(i+1);
}
return answer;
}
}
✏️ 풀이 과정
1. 정답을 저장하기 위한 arraylist, 약관별 유효기간을 저장하기 위한 Hashmap 생성
2. map 에 약관별 유효기간을 저장한다.
3. 각각의 변수에 년, 월, 일을 저장하고 언제까지 보관 가능한지 날짜를 구한다.
=> 유효한 날짜를 구하는 방법
1. 월에 유효기간을 더한다.
2. 월의 값이 12보다 크면: 년에는 month/12 한 값을 더하고, month의 값은 month%12 한 값으로 변경해준다.
=> month%12 한 값이 만약 0이라면 12월이므로 month 값은 12로, year은 -1 해준다.
4. 현재 날짜 기준으로 유효기간이 지났는지 확인하기 위해 check 함수를 호출한다.
5. 함수를 호출한 결과가 false이면 유효기간이 지났다는 뜻이므로, 이 경우에 answer에 개인 정보의 번호를 저장한다. (i는 0부터 시작이므로 +1 해줘야 함)
✍🏻 느낀점
이 문제는 어렵다기보다, 자잘자잘한 실수들을 많이 했다. 뭔가 카카오 문제는 split 함수를 써야되는? 유형의 문제를 좋아하는 것 같다. 항상 문제 형식이 이런식인듯..? 이번 문제로 split 함수를 사용하여 온점을 기준으로 구분하여 자를 때, 그냥 str.split(".") 이렇게 하면 안된다는 점을 새롭게 알게 됐다!!! 이렇게 하면 빈 배열이 리턴된다. str.split("[.]"); 또는 str.split("\\."); 이렇게 사용해야 올바른 결과가 나온다는 것을 처음 알게 되었다. 이거 때문에 뭐가 문제인지 몰라서 시간을 낭비하고, 월이 12월이 넘어갈 때, month%12의 값이 0일 때를 생각을 안해줘서 또 시간을 낭비했다 ㅎㅎ,, 이번 문제로 또 하나 배웠다.
참고 블로그
https://hianna.tistory.com/618 // 문자열 마침표로 구분하여 자르기