Reorder Data in Log Files

HeeSeong·2021년 8월 16일
0

LeetCode

목록 보기
9/38
post-thumbnail

🔗 문제 링크

https://leetcode.com/problems/reorder-data-in-log-files/


❔ 문제 설명


You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.

There are two types of logs:

  • Letter-logs: All words (except the identifier) consist of lowercase English letters.

  • Digit-logs: All words (except the identifier) consist of digits.
    Reorder these logs so that:

The letter-logs come before all digit-logs.

1. The letter-logs are sorted lexicographically by their contents. 
2. If their contents are the same, then sort them lexicographically by their identifiers.
3. The digit-logs maintain their relative ordering.

Return the final order of the logs.


⚠️ 제한사항


  • 1 <= logs.length <= 100

  • 3 <= logs[i].length <= 100

  • All the tokens of logs[i] are separated by a single space.

  • logs[i] is guaranteed to have an identifier and at least one word after the identifier.



💡 풀이 (언어 : Java)


배열 정렬 기준을 정의하는 comparator의 다중조건을 해결하는 문제이다. isDigit이라는 boolean 변수를 선언해서 각 원소의 타입이 digit인지 letter인지 체크한다. 각각의 결과에 따라서 -1, 0, 1을 return해주고 둘다 letter인 경우에 identifier 뒤의 내용을 compareTo로 비교해서 사전순으로 값을 return하고 나머지는 identifier를 기준으로 사전순으로 return한다.

import java.util.Arrays;
import java.util.Comparator;

class Solution {
    public String[] reorderLogFiles(String[] logs) {
        Arrays.sort(logs, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                String[] arr1 = o1.split(" ", 2), arr2 = o2.split(" ", 2);
                boolean isDigit1 = Character.isDigit(arr1[1].charAt(0)), isDigit2 = Character.isDigit(arr2[1].charAt(0));
                if (!isDigit1 && !isDigit2) {
                    if (arr1[1].compareTo(arr2[1]) == 0)
                        return arr1[0].compareTo(arr2[0]);
                    else
                        return arr1[1].compareTo(arr2[1]);
                }
                else if (!isDigit1 && isDigit2)
                    return -1;
                else if (isDigit1 && !isDigit2)
                    return 1;
                else
                    return 0;
            }
        });
        return logs;
    }
}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글