코딩테스트

[프로그래머스/Java] 개인정보 수집 유효기간 (split 개념)

데메즈 2026. 7. 9. 20:10
반응형

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

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

★ split()의 기본 사용법★

split("구분자") 는 문자열을 지정한 구분자로 잘라서 문자열 배열( String[] ) 로 반환해준다

String term = "A 6";
String[] parts = term.split(" "); // 공백을 기준으로 나눔

System.out.println(parts[0]); // 출력 : "A"
System.out.println(parts[1]); // 출력 : "6"

 

★ ★ 함정★ ★

date.split(".") 을 쓰면 아무것도 분리되지 않거나 에러가 난다

이유 : split() 함수는 내부적으로 정규식을 사용. 정규식에서 마침표(.)는 '모든 문자'를 뜻하는 기호로 인식

해결책 : 앞에 백슬래시 2개를 붙여서 \\. 로 표현해야 한다

String date = "2026.05.19";

String[] totalDate = date.split("\\.");

int year = Integer.parseInt(totalDate[0]); // 2026
int month = Integer.parseInt(totalDate[1]); // 5
int day = Integer.parseInt(totalDate{2]); // 19

 

풀이

import java.util.HashMap;
import java.util.ArrayList;

class Solution {
    public int[] solution(String today, String[] terms, String[] privacies) {
        
        // privacies 수집날짜 + 약관종류
        // terms 약관 + 유효기간
        HashMap<String,Integer> map = new HashMap<>();
        ArrayList<Integer> arrAnswer = new ArrayList<>();
        
        for(String term : terms){
            String kind = term.split(" ")[0];
            int month = Integer.parseInt(term.split(" ")[1]);
            map.put(kind, month);
        }
        
        for(int i=0; i<privacies.length; i++){
            String privacy = privacies[i];
            String date = privacy.split(" ")[0];
            String kind = privacy.split(" ")[1];
            int month = map.get(kind);
            // 오늘 >= 유효기간 -> 폐기
            if(calDateNum(today) >= calDateNum(date)+month*28){
                arrAnswer.add(i+1);
            }
        }
        
        int[] answer = new int[arrAnswer.size()];
        for(int i=0; i<arrAnswer.size(); i++){
            answer[i] = arrAnswer.get(i);
        }
        return answer;
    }
    
    private int calDateNum(String date){
        String[] arrDate = date.split("\\.");
        int year = Integer.parseInt(arrDate[0]);
        int month = Integer.parseInt(arrDate[1]);
        int day = Integer.parseInt(arrDate[2]);
        
        return year*12*28+month*28+day;
    }
}
반응형