- 난이도: Lv2
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/17686
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/2/[3차] 파일명 정렬
풀이 시간 : 35분
import java.util.*;
import java.util.regex.*;
class Solution {
public String[] solution(String[] files) {
Arrays.sort(files, (o1, o2) -> {
// 정규표현식 : HEAD, NUMBER 추출
Pattern pattern = Pattern.compile("^([^0-9]+)([0-9]{1,5})(.*)$");
Matcher m1 = pattern.matcher(o1);
Matcher m2 = pattern.matcher(o2);
m1.matches();
m2.matches();
String head1 = m1.group(1).toLowerCase();
String head2 = m2.group(1).toLowerCase();
int num1 = Integer.parseInt(m1.group(2));
int num2 = Integer.parseInt(m2.group(2));
// HEAD 먼저 비교
int headCompare = head1.compareTo(head2);
if (headCompare != 0) {
return headCompare;
}
// HEAD가 같으면 -> NUMBER 비교
return Integer.compare(num1, num2);
});
return files;
}
}
import java.util.*;
class Solution {
class FileInfo {
String head;
int number;
String original;
int index;
FileInfo(String original, int index) {
this.original = original;
this.index = index;
parseFile(original);
}
private void parseFile(String fileName) {
int i = 0;
StringBuilder headBuilder = new StringBuilder();
// HEAD
while (i < fileName.length() && !Character.isDigit(fileName.charAt(i))) {
headBuilder.append(fileName.charAt(i));
i++;
}
this.head = headBuilder.toString().toLowerCase();
// NUMBER
StringBuilder numberBuilder = new StringBuilder();
int count = 0;
while (i < fileName.length() && Character.isDigit(fileName.charAt(i)) && count < 5) {
numberBuilder.append(fileName.charAt(i));
i++;
count++;
}
this.number = Integer.parseInt(numberBuilder.toString());
}
}
public String[] solution(String[] files) {
List<FileInfo> fileList = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
fileList.add(new FileInfo(files[i], i));
}
// Comparator
fileList.sort(new Comparator<FileInfo>() {
@Override
public int compare(FileInfo f1, FileInfo f2) {
// HEAD 비교
int headCompare = f1.head.compareTo(f2.head);
if (headCompare != 0) {
return headCompare;
}
// HEAD가 같으면 NUMBER 비교
int numberCompare = Integer.compare(f1.number, f2.number);
if (numberCompare != 0) {
return numberCompare;
}
return Integer.compare(f1.index, f2.index);
}
});
return fileList.stream()
.map(f -> f.original)
.toArray(String[]::new);
}
}