CS/알고리즘_KAKAO BLIND RECRUITMENT

2018 KAKAO BLIND RECRUITMENT : [3차] 파일명 정렬

Jedy_Kim 2021. 11. 3. 13:52
728x90

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

 

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

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

programmers.co.kr

 

// 코드

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.*;
 
class Solution {
    
    
    // filename, heade, number 정보를 관리하는 클래스
    class File {
        String fileName;
        String head;
        int number;
        
        public File(String fileName, String head, int number) {
            this.fileName = fileName;
            this.head     = head;
            this.number   = number;
        }        
    }
    
    
    // Head와 Number로 분리한다.
    String[] splitFileName(String file) {
        
        String[] str = new String[3];
        str[0= "";
        str[1= "";
        str[2= "";
        
        int idx = 0;
        for(int i=0; i<file.length(); ++i) {
            
            char c = file.charAt(i);    
            // 문자인 경우 
            if( idx == 0 ) {
                if(!Character.isDigit(c)) str[idx] += c;
                else ++idx;
            }  
            // 숫자인 경우
            if( idx == 1 ) {
                if(Character.isDigit(c)) str[idx] += c;
                else ++idx;
            }    
            // 마지막 꼬리인 경우
            if( idx >= 2 ) str[idx] += c;            
        }
        
        // 문자열은 대/소문자를 구분하지 않으므로 소문자로 치환해서 반환한다.
        str[0= str[0].toLowerCase();
        return str;                
    }
    
    
    // main
    public String[] solution(String[] files) {
        
        // 파일객체들을 담는 배열
        File[] fileInfoArr = new File[files.length];
        
        for(int i=0; i<files.length++i) {
            String[] str   = splitFileName(files[i]); // 이름을 분리한다.
            fileInfoArr[i] = new File(files[i], str[0], Integer.parseInt(str[1])); // 파일배열에 파일 객체를 넣어준다.
        }
        
        // 문제에서 제시한 조건에 맞도록 정렬한다.
        Arrays.sort(fileInfoArr, new Comparator<File>() {           
            public int compare(File o1, File o2) {
                if( (o1.head).equals(o2.head) ) return o1.number - o2.number;
                else                            return (o1.head).compareTo(o2.head); 
            }            
        });
        
        // 정렬된 순을 answer 배열에 담아주고 반환한다.
        String[] answer = new String[files.length];
        for(int i=0; i<files.length++i) answer[i] = fileInfoArr[i].fileName;
        return answer;
    }
    
    
}
cs
반응형