프로그래머스 [3차] 파일명 정렬 JAVA

sundays·2022년 10월 1일
0

문제

[3차] 파일명 정렬

풀이

head, number, 순을 기준으로 정렬해야 한다.

  1. files 를 재정렬하는 것이 답이기 때문에 따로 공간복잡도를 높일 필요가 없다
		Arrays.sort(files, (o1, o2) -> {
            String head1 = o1.split("[0-9]")[0].toLowerCase();
            String head2 = o2.split("[0-9]")[0].toLowerCase();
            if (head1.compareTo(head2) == 0) {
                int number1 = getNumber(o1.substring(head1.length()));
                int number2 = getNumber(o2.substring(head2.length()));
                return number1 - number2;
            } else {

                return head1.compareTo(head2);
            }
        });
  • head 는 알파벳 순서대로 정렬하고 하고 number 는 숫자앞에 0을 제외하고 오름차순으로 정렬한다
  • split("[0-9]") 를 사용해서 숫자가 나오기전까지 값을 재 정의 해준다.
  • 값이 같은 경우에는 number 값을 비교하여 정렬을 해준다
  1. number를 가져오기 위해 isdigit 함수를 사용한다
	private static int getNumber(String s) {
        StringBuilder result = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                result.append(c);
            } else {
                return Integer.parseInt(result.toString());
            }
        }
        return Integer.parseInt(result.toString());
    }

isdigit 을 사용하여 숫자일 경우에만 append를 하고 숫자가 아닌 경우 바로 append된 값을 리턴 해주고 종료된다

전체 코드

전체 코드

profile
develop life

0개의 댓글