티스토리 뷰

728x90

0. 사용된 lambda는 

  0-1 정렬을 위하여 sorted(Comparator<T>)를 사용하였다.

  0-2 toArray는 배열을 생성하는데 내부적으로 IntFunction을 인자로 받는다. 

    0-2-1 IntFunction은 하나의 int 값을 인자로 받아 특정타입을 반환하는 함수이다.

    0-2-2 보통 인자는 생성할 배열의 크기가 되고 여기서는 new 메소드로 타입을 지정한다.

 

 

1. 이 문제는 정렬에 대한 문제이다.

 

937. Reorder Data in Log Files

 

You have an array of logs.  Each log is a space delimited string of words.

For each log, the first word in each log is an alphanumeric identifier.  Then, either:

  • Each word after the identifier will consist only of lowercase letters, or;
  • Each word after the identifier will consist only of digits.

We will call these two varieties of logs letter-logs and digit-logs.  It is guaranteed that each log has at least one word after its identifier.

Reorder the logs so that all of the letter-logs come before any digit-log.  The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties.  The digit-logs should be put in their original order.

Return the final order of the logs.

 

Example 1:

 

Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]

Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]

 

Constraints:

  1. 0 <= logs.length <= 100
  2. 3 <= logs[i].length <= 100
  3. logs[i] is guaranteed to have an identifier, and a word after the identifier.

2. 핵심은 Comparator<T> interface를 구현하는 것이다. 하나의 타입의 두개의 인자를 보통 제공한다.

  2-1 중요한 것은 항상 반환값 a, b를 비교할 때 음수를 반환하여야 a가 먼저 오게된다.

  2-2 양수는 b가 먼저 오게되고 0은 순서가 그대로 유지된다.

  2-3 첫번째 두번째 if는 두 타입이 다를 경우 문자가 무조건 우선하게 한다.

  2-4 세번째는

    2-4-1 두 타입이 동일한 경우인데, digit은 순서를 바꾸지 않으므로 0을 반환한다.

    2-4-2 마지막은 두 타입이 모두 letter인 경우인데 첫번째 두번째는 첫번째 keyword로 순서를 결정하고

      2-4-2-1 마지막은 첫번째 keyword가 같을 경우 log identifier를 비교하여 결정한다.

 

import java.util.Arrays;

public class App {
  public static void main(String[] args) throws Exception {
    String[] logs = { "dig1 8 1 5 1", "let1 art can", "dig2 3 6", "let2 own kit dig", "let3 art zero" };
    Solution sol = new Solution();
    String[] list = sol.reorderLogFiles(logs);

    Arrays.stream(list).forEach(str-> System.out.println(str));
  }
}

class Solution {
  public String[] reorderLogFiles(String[] logs) {

    return Arrays.stream(logs).sorted((a, b) -> {
      String[] split1 = a.split(" ");
      String[] split2 = b.split(" ");

      if (split1[0].startsWith("let") && split2[0].startsWith("dig")) {
        return -1;
      } else if (split2[0].startsWith("let") && split1[0].startsWith("dig")) {
        return 1;
      } else {
        if (split1[0].startsWith("dig")) {
          return 0;
        } else {
          if (split1[1].compareTo(split2[1]) > 0) {
            return 1;
          } else if (split1[1].compareTo(split2[1]) < 0) {
            return -1;
          } else {
            if (split1[0].compareTo(split2[0]) > 1) {
              return 1;
            } else {
              return -1;
            }
          }
        }
      }
    }).toArray(size -> new String[size]);
  }
}

 

3. 결과 화면

 

728x90

'Basic > Algorithms' 카테고리의 다른 글

LeetCode 1041. Robot Bounded In Circle  (0) 2022.06.24
Questions : Partition Labels  (0) 2020.07.25
Questions : Number of Islands  (0) 2020.07.25
Questions : 자동완성  (0) 2020.07.25
Questions : Critical Connections  (0) 2020.07.24
댓글