https://school.programmers.co.kr/learn/courses/30/lessons/150370
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 풀이
알고리즘이 들어가지 않은 기본적인 구현 문제라 크게 어렵진 않았을 것이다. 문자열을 분리하여 년, 월, 일을 구분하고 두 날짜의 차이를 구할 수 있다면 쉽게 해결할 수 있다.
필자는 두 날짜의 차이를 구하기 위해 일(day)로 변환하는 작업을 진행했다. 기본적으로 today가 privacy의 날짜보다 더 크다.
또한 약관 terms는 Map에 저장하여 파기해야 하는 정보인지 비교할 때 꺼내서 사용하였다.
날짜를 년, 월, 일로 구분하기 위해 String.split()을 사용했는데 "."으로 나누는 과정에서 막혔었다.
split의 파라미터에는 정규식이 들어가기 때문에 '.'은 정규식에서 문자를 의미한다. 우리가 원하는 '.'으로 분리하기 위해선 [.]으로 기재해야 한다.
코드
class Solution {
static List<Integer> answer = new ArrayList<>();
static HashMap<Character, Integer> termMap = new HashMap<>();
public int[] solution(String today, String[] terms, String[] privacies) {
for (String term : terms) {
String[] split = term.split(" ");
termMap.put(split[0].charAt(0), Integer.valueOf(split[1]));
}
for (int i = 0; i < privacies.length; i++) {
checkDestroyed(today, privacies[i], i + 1);
}
return answer.stream().mapToInt(Integer::intValue).toArray();
}
static void checkDestroyed(String today, String privacy, int seq) {
String[] todaySplit = today.split("[.]");
int todayYear = Integer.parseInt(todaySplit[0]);
int todayMon = Integer.parseInt(todaySplit[1]);
int todayDay = Integer.parseInt(todaySplit[2]);
String[] privacySplit = privacy.split(" ");
String[] privacyDate = privacySplit[0].split("[.]");
char term = privacySplit[1].charAt(0);
int privacyYear = Integer.parseInt(privacyDate[0]);
int privacyMon = Integer.parseInt(privacyDate[1]);
int privacyDay = Integer.parseInt(privacyDate[2]);
// year 맞추기
todayMon += (todayYear - privacyYear) * 12;
// mon 맞추기
todayDay += (todayMon - privacyMon) * 28;
int termMon = termMap.get(term);
if ((todayDay - privacyDay) >= termMon * 28) {
answer.add(seq);
}
}
}
'Coding Test > 프로그래머스' 카테고리의 다른 글
[2023 KAKAO BLIND RECRUITMENT] 이모티콘 할인행사 - 자바 (0) | 2023.10.15 |
---|---|
[프로그래머스] 가장 먼 노드 - 자바 (0) | 2023.08.20 |
[프로그래머스] 입국심사 - 자바 (1) | 2023.08.19 |
[프로그래머스] 네트워크 - 자바 (2) | 2023.08.19 |
[프로그래머스] 여행경로 - 자바 (0) | 2023.08.18 |