2026.03.16
소요 시간: 1시간
나의 정답
알고리즘은 맞았지만, 코드로 구현하는 과정에서nullPointerException등과 같은 문제가 다수 발생해서 오류를 찾는 데에 좀 고생을 했다.
코딩할 때에 집중해서 해야한다.import java.util.Map; import java.util.HashMap; class Solution { public int[] solution(String today, String[] terms, String[] privacies) { int answer[] = new int[privacies.length]; int index = 0; int currentDate = Integer.parseInt(today.replace(".", "")); Map<String, Integer> saveOption = new HashMap<>(); for (int i = 0; i < terms.length; i++) { String split[] = terms[i].split(" "); String option = split[0]; int period = Integer.parseInt(split[1]); saveOption.put(option, period); } for (int i = 0; i < privacies.length; i++) { String split[] = privacies[i].split(" "); String savedDate[] = split[0].split("\\."); String option = split[1]; int year = Integer.parseInt(savedDate[0]); int month = Integer.parseInt(savedDate[1]); int date = Integer.parseInt(savedDate[2]); int savePeriod = saveOption.get(option); year += savePeriod / 12; month += savePeriod % 12; if (month > 12) { year += 1; month -= 12; } date -= 1; if (date <= 0) { if (month == 1) { year -= 1; month = 12; date = 28; } else { month -= 1; date= 28; } } int expirationDate = Integer.parseInt(String.format("%d%02d%02d", year, month, date)); if (currentDate > expirationDate) { answer[index++] = i + 1; } } int result[] = new int[index]; for (int i = 0; i < result.length; i++) { result[i] = answer[i]; } return result; } }
AI 정답
코드를 간결하게 짜려면 수학적으로 사고하는 방법이 중요함
getDays년, 월, 일을.으로 구분하여 총 일수를 반환하는 메서드import java.util.*; class Solution { public int[] solution(String today, String[] terms, String[] privacies) { // 1. 오늘 날짜를 총 일수로 변환 int todayDays = getDays(today); // 2. 약관 정보를 Map에 저장 Map<String, Integer> termMap = new HashMap<>(); for (String term : terms) { String[] s = term.split(" "); termMap.put(s[0], Integer.parseInt(s[1]) * 28); // 월을 일수로 미리 계산 } List<Integer> expiredList = new ArrayList<>(); // 3. 개인정보 만료 여부 확인 for (int i = 0; i < privacies.length; i++) { String[] s = privacies[i].split(" "); int collectedDays = getDays(s[0]); int termDays = termMap.get(s[1]); // 만료일 = 수집일 + 유효기간 // 만약 만료일이 오늘보다 작거나 같다면? (오늘 날짜가 만료일 이후라면 파기) if (collectedDays + termDays <= todayDays) { expiredList.add(i + 1); } } // 4. 리스트를 배열로 변환 return expiredList.stream().mapToInt(Integer::intValue).toArray(); } // 날짜 문자열을 총 일수로 바꾸는 헬퍼 함수 private int getDays(String date) { String[] parts = date.split("\\."); int y = Integer.parseInt(parts[0]); int m = Integer.parseInt(parts[1]); int d = Integer.parseInt(parts[2]); return (y * 12 * 28) + (m * 28) + d; } }