[LeetCode] 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.

重新排列日志文件。分两种日志,一种是字母日志,一种是数字日志。每个日志的第一个单词决定了他到底是字母日志还是数字日志,请按如下规则对日志排序。

  • 所有 字母日志 都排在 数字日志 之前。
  • 字母日志 在内容不同时,忽略标识符后,按内容字母顺序排序;在内容相同时,按标识符排序;
  • 数字日志 应该按原来的顺序排列。

思路是需要自己写comparator函数。

时间O(nlogn)

空间O(n)

Java实现

 1 class Solution {
 2     public String[] reorderLogFiles(String[] logs) {
 3         List<String> llogs = new ArrayList<>();
 4         List<String> dlogs = new ArrayList<>();
 5         for (String log : logs) {
 6             int i = log.indexOf(" ");
 7             char ch = log.charAt(i + 1);
 8             if (ch >= '0' && ch <= '9') {
 9                 dlogs.add(log);
10             } else {
11                 llogs.add(log);
12             }
13         }
14         Collections.sort(llogs, new Comparator<String>() {
15             @Override
16             public int compare(String s1, String s2) {
17                 int index1 = s1.indexOf(" ");
18                 String id1 = s1.substring(0, index1);
19                 String letter1 = s1.substring(index1 + 1);
20                 int index2 = s2.indexOf(" ");
21                 String id2 = s2.substring(0, index2);
22                 String letter2 = s2.substring(index2 + 1);
23                 int v1 = letter1.compareTo(letter2);
24                 if (v1 != 0) {
25                     return v1;
26                 }
27                 int v2 = id1.compareTo(id2);
28                 return v2;
29             }
30         });
31         String[] res = new String[llogs.size() + dlogs.size()];
32         int i = 0;
33         for (String s : llogs) {
34             res[i++] = s;
35         }
36         for (String s : dlogs) {
37             res[i++] = s;
38         }
39         return res;
40     }
41 }

 

LeetCode 题目总结

posted @ 2020-06-08 11:31  CNoodle  阅读(168)  评论(0编辑  收藏  举报