antop-dev / algorithm

알고리즘 풀이
MIT License
0 stars 0 forks source link

파일명 정렬 #568

Closed antop-dev closed 3 months ago

antop-dev commented 3 months ago

https://school.programmers.co.kr/learn/courses/30/lessons/17686

antop-dev commented 3 months ago

주의사항

Java:

import java.util.Arrays;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Solution {
    public String[] solution(String[] files) {
        var pattern = Pattern.compile("^([a-zA-Z\\-\\s]+)([0-9]{1,5})(.*)$");
        return Arrays.stream(files)
                // 정규식 추출
                .map(pattern::matcher)
                .filter(Matcher::find)
                // 정렬
                .sorted(Comparator
                        .comparing((Matcher m) -> m.group(1).toLowerCase())
                        .thenComparingInt(m -> Integer.parseInt(m.group(2)))
                )
                // 원래 파일명으로 변환
                .map(m -> m.group(0))
                // String[]으로 변환
                .toArray(String[]::new);
    }
}

Python:

import re

def solution(files):
    ans = map(lambda x: re.match("^([a-zA-Z\\-\\s]+)(\\d{1,5})(.*)$", x), files)
    ans = map(lambda m: [m.group(0), m.group(1).lower(), int(m.group(2))], ans)
    ans = sorted(ans, key=lambda x: (x[1], x[2]))
    ans = map(lambda x: x[0], ans)
    ans = list(ans)
    return ans