프로그래머스 | 파일명 정렬 (Java)

mul·2023년 3월 15일
0

코딩테스트연습

목록 보기
39/56

🔒 문제

프로그래머스 Lv.2 2018 KAKAO BLIND RECRUITMENT [3차] 파일명 정렬

🔑 해결

파일명에 포함된 숫자를 반영한 정렬 기능을 구현하여, 입력으로 문자열 배열 files가 주어지면 파일명을 세 부분으로 나눈 후 기준에 따라 파일명을 정렬하여 배열에 담아 return하는 solution함수를 작성하는 문제이다.

파일명을 HEAD, NUMBER, TAIL 세 부분으로 나누어 HEAD와 NUMBER을 통해 다른 파일명과 비교해야 하기 때문에 파일명과 HEAD, NUMBER를 담는 Record 클래스를 만들어 사용하였다.
Comparator를 Override하여 record의 head부분을 비교하고, head부분이 같으면 number을 비교하여 return하도록 하였다.
파일명을 head와 number 부분으로 나눌 때, 반복문의 조건 설정을 제대로 해주지 않으면 런타임 에러가 발생한다. 조건과 범위를 수정해주니 제대로 동작하였다.

🔓 코드

import java.util.Arrays;
import java.util.Comparator;
class Solution {
    private class Record{
		String file;
		String head;
		int number;
		
		public Record(String file, String head, int number) {
			super();
			this.file = file;
			this.head = head;
			this.number = number;
		}
		
		
	}
	
    public String[] solution(String[] files) {
        String[] answer = new String[files.length];
        
        Record[] record = new Record[files.length];
        for (int i = 0; i < files.length; i++) {
			String[] hnt = find_hnt(files[i]);
			Record r = new Record(files[i], hnt[0], Integer.parseInt(hnt[1]));
			record[i] = r;
		}
        
        Arrays.sort(record, new Comparator<Record>() {
			@Override
			public int compare(Record o1, Record o2) {
				if (o1.head.equals(o2.head)) {
					return o1.number - o2.number;
				} else {
					return o1.head.compareTo(o2.head);
				}
			}
		});
        
        for (int i = 0; i < record.length; i++) {
			answer[i] = record[i].file;
		}
        
        return answer;
    }
    
    private String[] find_hnt(String str) {
		int[] hnt = new int[2];
		
		int i = 0;
		while(i < str.length() && (str.charAt(i) < '0' || str.charAt(i) > '9')) {
			i++;
		}
		hnt[0] = i;
		
		int j = i;
		int count = 0;
		while(j < str.length() && (str.charAt(j) >= '0' && str.charAt(j) <= '9')) {
			if (count == 5)
				break;
			j++;
			count++;
		}
		hnt[1] = j;
		
		String head = str.substring(0, hnt[0]);
		head = head.toLowerCase();
        String number = str.substring(hnt[0], hnt[1]);
        
        String[] shn = {head, number};
        
        return shn;
	}
}


💭 Arrays의 sort메서드를 사용해 정렬하는 것은 많이 해보았지만, Comparator을 익명함수로 만들어 오버라이드 해 정렬하는 것은 처음 해보았다. 어렵지 않지만 낯설었다.

0개의 댓글