programmers_[3차] 파일명 정렬_java
2023. 4. 11. 18:40ㆍAlgorithm/Programmers
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/17686
import java.util.*;
class Solution {
public String[] solution(String[] files) {
int filesLength = files.length;
String[] answer = new String[filesLength];
PriorityQueue<FileName> pq = new PriorityQueue<>();
for(int i = 0; i<filesLength; i++){
String[] file = splitFile(files[i]);
pq.offer(new FileName(files[i],file[0], file[1], file[2], i));
}
int idx = 0;
while(!pq.isEmpty()){
FileName now = pq.poll();
answer[idx++] = now.original;
}
return answer;
}
public String[] splitFile(String file){
String[] splitFile = new String[3];
int fileLength = file.length();
int tailStartIdx = fileLength;
int numberStartIdx = 0;
for(int i = 0; i<fileLength; i++){
if(numberStartIdx == 0 && ('0' <= file.charAt(i) && file.charAt(i) <= '9') ){// numberStartIdx 찾기
numberStartIdx = i;
}
else if(numberStartIdx != 0 && ('0' > file.charAt(i) || file.charAt(i) > '9')){ //tailStartIdx 찾기
tailStartIdx = i;
break;
}
}
splitFile[0] = file.substring(0, numberStartIdx);
splitFile[1] = file.substring(numberStartIdx, tailStartIdx);
splitFile[2] = file.substring(tailStartIdx);
return splitFile;
}
public class FileName implements Comparable<FileName>{
String head, number, tail, original;
int idx; // 들어온 순서
public FileName(String original, String head, String number, String tail, int idx){
this.original = original;
this.head = head.toLowerCase();
this.number = number;
this.tail = tail.toLowerCase();
this.idx = idx;
}
@Override
public int compareTo(FileName o){
if(head.compareTo(o.head) > 0){
return 1;
}else if(head.compareTo(o.head) < 0){
return -1;
}else{
if(Integer.parseInt(number) - Integer.parseInt(o.number) > 0){
return 1;
}else if(Integer.parseInt(number) - Integer.parseInt(o.number) < 0){
return -1;
}else{
return idx - o.idx;
}
}
}
@Override
public String toString(){
return " " + head + " " + number + " " + tail + " " + idx + " " + original;
}
}
}
'Algorithm > Programmers' 카테고리의 다른 글
programmers_[1차] 프렌즈4블록_java (0) | 2023.04.13 |
---|---|
programmers_게임 맵 최단거리_java (0) | 2023.04.11 |
programmers_모음 사전_java (0) | 2023.04.11 |
programmers_방문 길이_java (0) | 2023.04.11 |
programmers_스킬트리_java (1) | 2023.04.10 |