-
[string] reorder data in log filesAlgorithm/LeetCode 2025. 3. 9. 10:12
✅ Problem
https://leetcode.com/problems/reorder-data-in-log-files/description/
✅ Approach & Solution
방식)
더보기문제 조건
- 로그의 가장 앞부분은 식별자로서, 순서에 영향을 끼치지 않는다.
- 문자로 구성된 로그가 숫자 로그보다 앞에 오며, 문자 로그는 사전순으로 한다.
- 문자가 동일한 경우에는 식별자순으로 한다.
- 숫자 로그는 입력 순서대로 한다.
풀이
- 로그 나누기 (문자 로그, 숫자 로그)
- 로그 정렬 (문자 로그만 정렬 수행)
- 로그 합친 후 반환
class Solution { public String[] reorderLogFiles(String[] logs) { List<String> digitLogs = new ArrayList<>(); List<String> letterLogs = new ArrayList<>(); // 로그 나누기 for (String log : logs) { if (Character.isDigit(log.split(" ")[1].charAt(0))) { digitLogs.add(log); } else { letterLogs.add(log); } } // 로그 정렬 letterLogs.sort((s1, s2) -> { // 식별자와 식별자 아닌 부분으로 나누기 String[] s1x = s1.split(" ", 2); String[] s2x = s2.split(" ", 2); int compared = s1x[1].compareTo(s2x[1]); if (compared == 0) { return s1x[0].compareTo(s2x[0]); } else { return compared; } }); // 로그 합치기 letterLogs.addAll(digitLogs); return letterLogs.toArray(new String[0]); } }
'Algorithm > LeetCode' 카테고리의 다른 글
[array] container with most water (0) 2025.03.22 [string] most common word (0) 2025.03.09 [string] reverse string (0) 2025.03.08 [string] valid palindrome (0) 2025.03.08 [array] merge sorted array (0) 2025.02.22