https://school.programmers.co.kr/learn/courses/30/lessons/17686
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
파일명을 일정한 규칙에 따라 3부분으로 나누고 정렬해야하므로 일단 파일명 분리가 필요하다.
그래서 정규식을 사용했다.
숫자를 제외한 문자로 한개 이상의 문자열([^0-9]*)
숫자로만 이루어진 1~5개의 문자열([0-9]{1,5})
그외 나머지(.*)
이렇게 나누어진 부분을 주어진 규칙으로 정렬하면 끝
import java.util.*;
import java.util.regex.*;
class Solution {
public String[] solution(String[] files) {
List<FileInfo> infos = new ArrayList();
for (int i = 0; i < files.length; i++) {
String fileName = files[i];
FileInfo info = FileInfo.from(i, fileName);
infos.add(info);
}
return infos.stream()
.sorted()
.map(i -> i.fileName)
.toArray(String[]::new);
}
static class FileInfo implements Comparable<FileInfo> {
static final Pattern p = Pattern.compile("([^0-9]+)([0-9]{1,5})(.*)");
int index;
String fileName;
String head;
int number;
String tail;
static FileInfo from(int index, String fileName) {
FileInfo vo = new FileInfo();
vo.index = index;
vo.fileName = fileName;
Matcher m = p.matcher(fileName);
if (m.matches()) {
vo.head = m.group(1).toLowerCase();
vo.number = Integer.parseInt(m.group(2));
if (m.groupCount() == 3) {
vo.tail = m.group(3);
} else {
vo.tail = "";
}
}
return vo;
}
public int compareTo(FileInfo o) {
int compare = this.head.compareTo(o.head);
if (compare != 0) return compare;
compare = this.number - o.number;
if (compare != 0) return compare;
return this.index - o.index;
}
}
}