레벨업 일지

[Java] 프로그래머스 개인정보 수집 유효기간 본문

알고리즘/프로그래머스

[Java] 프로그래머스 개인정보 수집 유효기간

24시간이모자란 2023. 1. 28. 00:42

문제

2023 카카오 기출 문제

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

 

프로그래머스

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

programmers.co.kr

알아야 할 개념

  • 해시맵

풀이

로직은 다음과 같다. 

  1. 주어진 유효기한을 <문자열, 정수> 로 해싱한다. 
  2. 주어진 날자 포맷을 "yyyy-mm-dd" 에서 "dd" 로 계산한다. 
  3. today 보다 작거나 같은 날짜들을 정답 리스트에 담고 리턴한다. 

참고

https://stackoverflow.com/questions/14833008/java-string-split-with-dot

 

Java string split with "." (dot)

Why does the second line of this code throw ArrayIndexOutOfBoundsException? String filename = "D:/some folder/001.docx"; String extensionRemoved = filename.split(".")[0]; While this works: String

stackoverflow.com

자바에서는 String.split() 메소드를 사용할 때, 정규화 엔진에서  '.'  점 기호는 스페셜 문자로 구분한다. 스페셜 문자 파싱을 피하기 위해서 "\\" 문자열을  escape 문자로 사용해야한다. (여기서 막힌 사람들도 많을 것이다) 

x.split("\\.")[0]

 

다음과 같이 stream 클래스를 사용하여 ArrayList를 array로 convert 하였다. 

        return list.stream().mapToInt(x->x).toArray();

코드

자바

import java.util.*;

class Solution {
    int len;
    public int[] solution(String today, String[] terms, String[] privacies) {
        //파기해야 할 개인정보 번호를 오름차순 정렬해서 리턴할것. 
        len = privacies.length;
        
        HashMap<String, Integer> terM = new HashMap<>();
        int[] expireT = new int[len];
        
        ArrayList<Integer> list = new ArrayList<>();
        int now = getDays(today);
        for(String x : terms){
            terM.put(x.split(" ")[0], Integer.parseInt(x.split(" ")[1]) * 28);
        }
        
        for(int i =0 ;i < len ;i++){
            int day = getDays(privacies[i].split(" ")[0]);
            String key = privacies[i].split(" ")[1];
            expireT[i] = day + terM.get(key);
            //System.out.println(now+","+expireT[i]);
            if(expireT[i] <= now){
                list.add(i+1);
            }
        }
        return list.stream().mapToInt(x->x).toArray();
    }
    public int getDays(String x){
        int y = Integer.parseInt(x.split("\\.")[0]);
        int m = Integer.parseInt(x.split("\\.")[1]);
        int d = Integer.parseInt(x.split("\\.")[2]);
        
        return d + m * 28 + (y-2000) * 12 * 28;
    }
}
Comments