문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/17683
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드:
import java.util.*;
class Song implements Comparable<Song>{
String name;
int time;
public Song(String name, int time) {
this.name = name;
this.time = time;
}
// Collections.sort()는 stable sort 여서 따로 입력된 음악 순서를 비교하지 않았다
@Override
public int compareTo(Song o) {
return o.time - time;
}
}
class Solution {
public String solution(String m, String[] musicinfos) {
ArrayList<Song> list = new ArrayList<>();
for (int i = 0; i < musicinfos.length; i++) {
String[] split = musicinfos[i].split(",");
String startTime = split[0];
String endTime = split[1];
int time = calc(startTime, endTime);
String name = split[2];
String song = split[3];
String fullSong = fullTimeSong(time, song);
if (fullSong.contains(change(m))) {
list.add(new Song(name, time));
}
}
if (list.isEmpty()) {
return "(None)";
}else{
Collections.sort(list);
return list.get(0).name;
}
}
// C# -> c (#있는 음을 소문자로 변경)
private String change(String song) {
song = song.replaceAll("C#", "c");
song = song.replaceAll("D#", "d");
song = song.replaceAll("F#", "f");
song = song.replaceAll("G#", "g");
song = song.replaceAll("A#", "a");
return song;
}
// 시간만큼 음악 재생
private String fullTimeSong(int time, String song) {
StringBuilder sb = new StringBuilder();
String changeSong = change(song);
int t = time / changeSong.length();
int h = time % changeSong.length();
for (int i = 0; i < t; i++) {
sb.append(changeSong);
}
sb.append(changeSong, 0, h);
return sb.toString();
}
private int calc(String start, String end) {
int endTime = Integer.parseInt(end.split(":")[0]) * 60 + Integer.parseInt(end.split(":")[1]);
int startTime = Integer.parseInt(start.split(":")[0]) * 60 + Integer.parseInt(start.split(":")[1]);
return endTime - startTime;
}
}
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
String m = "CC#BCC#BCC#BCC#B";
String[] musicinfos = {"03:00,03:30,FOO,CC#B", "04:00,04:08,BAR,CC#BCC#BCC#B"};
String answer = sol.solution(m, musicinfos);
System.out.println("answer = " + answer);
}
}
'PS > 프로그래머스' 카테고리의 다른 글
프로그래머스 2019 KAKAO BLIND RECRUITMENT - 오픈채팅방[JAVA] (0) | 2023.10.26 |
---|---|
프로그래머스 2019 KAKAO BLIND RECRUITMENT - 실패율[JAVA] (0) | 2023.10.25 |
프로그래머스 2018 KAKAO BLIND RECRUITMENT - 압축[JAVA] (1) | 2023.10.23 |
프로그래머스 2018 KAKAO BLIND RECRUITMENT - N진수 게임[JAVA] (1) | 2023.10.21 |
프로그래머스 2018 KAKAO BLIND RECRUITMENT - 셔틀버스[JAVA] (1) | 2023.10.19 |