본문 바로가기
Problem Solving

[프로그래머스] L2 파일명 정렬 / 2018 카카오 블라인드 채용 (Java)

by JYHAN 2020. 12. 19.

카카오

[프로그래머스] L2 파일명 정렬 / 2018 카카오 블라인드 채용

[풀이]

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
59
60
import java.util.*;
class Solution {
    class HN implements Comparable<HN> {
        String head, num, tail;
        String h;
        int n;
        public HN(String head, String num, String tail){
            this.head = head;
            this.num = num;
            this.tail = tail;
            this.h = head.toUpperCase(); // 대문자로 변환(정렬)
            this.n = Integer.parseInt(num);
        }
        
        int ret = 0;
        @Override
        public int compareTo(HN hn) {
            if(this.h.compareTo(hn.h) < 0) {
                return -1;
            }else if(this.h.compareTo(hn.h) == 0){
                return this.n - hn.n;
            }else{
                ret = 1;
            }
            return ret;
        }
    }
    public String[] solution(String[] files) {
        List<HN> list = new ArrayList<HN>();
        for(String file : files){
            int headLastIdx = -1, numLastIdx = -1;
            for(int i=0; i<file.length(); i++){
                if(headLastIdx==-1 && ('0'<= file.charAt(i) && file.charAt(i)<='9'))
                    headLastIdx = i;
                else if(headLastIdx!=-1 && numLastIdx==-1 && (file.charAt(i)<'0' || '9'<file.charAt(i))){
                    numLastIdx = i;
                    break;
                }
            }
            String head = file.substring(0, headLastIdx);
            String num = "";
            String tail = "";
            if(numLastIdx==-1) {
                num = file.substring(headLastIdx);
            }else {
                num = file.substring(headLastIdx, numLastIdx);
                tail = file.substring(numLastIdx);
            }
            list.add(new HN(head, num, tail));
        }
        Collections.sort(list);
        String[] answer = new String[list.size()];
        for(int i=0; i<list.size(); i++){
            String ans = list.get(i).head + list.get(i).num + list.get(i).tail;
            answer[i] = ans;
        }
        
        return answer;
    }
}
cs

댓글