본문 바로가기
Java/알고리즘

[Java] 프로그래머스 Lv2 - 2018 KAKAO BLIND RECRUITMENT[3차] 파일명 정렬

by WaterPunch 2024. 12. 8.

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class FileNameSort {

    public ArrayList<ExampleFile> fileList = new ArrayList<>();

    public class ExampleFile implements Comparable<ExampleFile> {

        public int idx;
        public String head;
        public int number;
        public String tail;
        public String result;

        //생성자를 통한 데이터 입력방식 (Getter, Setter 생략)
        public ExampleFile(int idx, String head, String number, String tail) {
            this.idx = idx;
            this.head = head.toLowerCase();
            this.number = Integer.parseInt(number);
            this.tail = tail.toLowerCase();
            this.result = head + number + tail;
        }

        // 클래스 정렬 기준 (head -> number -> index)
        @Override
        public int compareTo(ExampleFile o) {
            if (this.head.equals(o.head)) {
                if (this.number == o.number) {
                    return this.idx - o.idx;
                }
                return this.number - o.number;
            }
            return this.head.compareTo(o.head);
        }
    }

    public String[] solution(String[] files) {
        // for문 1바퀴 돌때마다 idx + 1
        int idx = 0;
        for (String file : files) {
            StringBuilder head = new StringBuilder();
            StringBuilder number = new StringBuilder();
            StringBuilder tail = new StringBuilder();
            boolean tailAppend = false;
            for(int i=0; i<file.length(); i++) {
                if (tailAppend) {
                    tail.append(file.charAt(i));
                    continue;
                }

                // 해당문자가 숫자일때
                if(file.charAt(i) >= '0' && file.charAt(i) <= '9') {
                    number.append(file.charAt(i));
                    // Number 다음의 char가 문자열이라면 tail로 간주
                    if(i+1 < file.length() && !(file.charAt(i+1) >= '0' && file.charAt(i+1) <= '9')) {
                        tailAppend = true;
                    }
                } else {
                    head.append(file.charAt(i));
                }
            }
            fileList.add(new ExampleFile(idx, head.toString(), number.toString(), tail.toString()));
        }

        // compareTo로 정의한 정렬 방식
        Collections.sort(fileList);

        String[] answer = new String[fileList.size()];
        for (int i=0; i<fileList.size(); i++) {
            ExampleFile exampleFile = fileList.get(i);
            answer[i] = exampleFile.result;
        }
        return answer;
    }
}
반응형

댓글