프로그래밍 공방

[프로그래머스] 파일명 정렬 본문

개발/문제해결

[프로그래머스] 파일명 정렬

hyosupsong 2021. 2. 10. 20:04

문제

programmers.co.kr/learn/courses/30/lessons/17686

 

코딩테스트 연습 - [3차] 파일명 정렬

파일명 정렬 세 차례의 코딩 테스트와 두 차례의 면접이라는 기나긴 블라인드 공채를 무사히 통과해 카카오에 입사한 무지는 파일 저장소 서버 관리를 맡게 되었다. 저장소 서버에는 프로그램

programmers.co.kr

문제해결방법

각 파일명을 입력받아 HEAD, NUMBER와 들어온 순서를 기록하고 각 파일의 해당 값들을 비교하며 정렬해준다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package Programmers;
 
import java.util.Arrays;
import java.util.PriorityQueue;
 
class File implements Comparable<File> {
    String fileName;
    String head;
    int number;
    int originNum;
    
    File(String fileName, int index) {
        this.fileName = fileName;
        this.originNum = index;
        int s = 0, e = 0;
        for(int i=0; i<fileName.length(); i++) {
            if(fileName.charAt(i)>='0' && fileName.charAt(i)<='9') {
                e = i;
                break;
            }
        }
        this.head = fileName.substring(s, e).toLowerCase();
        s = e;
        for(int i=s; i<fileName.length(); i++) {
            if(fileName.charAt(i)<'0' || fileName.charAt(i)>'9') {
                e = i;
                break;
            }
        }
        if(s==e) e = fileName.length();
        this.number = Integer.parseInt(fileName.substring(s, e));
    }
    
    @Override
    public int compareTo(File arg0) {
        if(arg0.head.equals(this.head)) {
            if(arg0.number==this.number) return Integer.compare(this.originNum, arg0.originNum);
            else return Integer.compare(this.number, arg0.number);
        }
        return this.head.compareTo(arg0.head);
    }
}
 
public class Solution_파일명정렬 {
 
    public static String[] solution(String[] files) {
        PriorityQueue<File> pq = new PriorityQueue<File>();
        for(int i=0; i<files.length; i++) pq.add(new File(files[i], i));
        String[] answer = new String[pq.size()];
        for(int i=0; i<answer.length; i++) answer[i] = pq.poll().fileName;
        return answer;
    }
    
    public static void main(String[] args) {
        String[] files = {"F-5 Freedom Fighter""B-50 Superfortress""A-10 Thunderbolt II""F-14 Tomcat"};
        System.out.println(Arrays.toString(solution(files)));
    }
}
cs


코드에 대한 피드백이나 더 좋은 아이디어는 언제나 환영입니다.

'개발 > 문제해결' 카테고리의 다른 글

[프로그래머스] n진수 게임  (0) 2021.02.12
[백준] 1561번 : 놀이 공원  (0) 2021.02.10
[프로그래머스] 방금그곡  (0) 2021.02.10
[프로그래머스] 실패율  (0) 2021.02.10
[프로그래머스] 다트 게임  (0) 2021.02.10