|
| 1 | +package algorithm.easy.p937; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * https://leetcode.com/problems/reorder-data-in-log-files/ |
| 7 | + * 2 ms / 38.9 MB |
| 8 | + */ |
| 9 | +public class Solution { |
| 10 | + public String[] reorderLogFiles(String[] logs) { |
| 11 | + PriorityQueue<LettersLog> lettersQueue = new PriorityQueue<>(logs.length); |
| 12 | + List<String> digitLogs = new ArrayList<>(logs.length); |
| 13 | + |
| 14 | + for (String log : logs) { |
| 15 | + // split to identifier, contents |
| 16 | + int idx = log.indexOf(' '); |
| 17 | + String identifier = log.substring(0, idx); |
| 18 | + String contents = log.substring(idx + 1); |
| 19 | + |
| 20 | + // check letters-logs or digit-logs |
| 21 | + if (isDigitLogs(contents)) { |
| 22 | + digitLogs.add(log); |
| 23 | + continue; |
| 24 | + } |
| 25 | + lettersQueue.offer(new LettersLog(log, identifier, contents)); |
| 26 | + } |
| 27 | + |
| 28 | + String[] ret = new String[logs.length]; |
| 29 | + int idx = 0; |
| 30 | + while (!lettersQueue.isEmpty()) { |
| 31 | + LettersLog log = lettersQueue.poll(); |
| 32 | + ret[idx++] = log.origin; |
| 33 | + } |
| 34 | + |
| 35 | + for (String log : digitLogs) { |
| 36 | + ret[idx++] = log; |
| 37 | + } |
| 38 | + return ret; |
| 39 | + } |
| 40 | + |
| 41 | + static boolean isDigitLogs(String log) { |
| 42 | + for (int i = 0; i < log.length(); i++) { |
| 43 | + char ch = log.charAt(i); |
| 44 | + if (ch != ' ' && !Character.isDigit(ch)) { |
| 45 | + return false; |
| 46 | + } |
| 47 | + } |
| 48 | + return true; |
| 49 | + } |
| 50 | + |
| 51 | + static class LettersLog implements Comparable<LettersLog> { |
| 52 | + String origin; |
| 53 | + String identifier; |
| 54 | + String contents; |
| 55 | + |
| 56 | + public LettersLog(String origin, String identifier, String contents) { |
| 57 | + this.origin = origin; |
| 58 | + this.identifier = identifier; |
| 59 | + this.contents = contents; |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public int compareTo(LettersLog o) { |
| 64 | + int cmp = contents.compareTo(o.contents); |
| 65 | + if (cmp != 0) { |
| 66 | + return cmp; |
| 67 | + } |
| 68 | + return identifier.compareTo(o.identifier); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + public static void main(String[] args) { |
| 73 | + // String[] logs = { "dig1 8 1 5 1", "let1 art can", "dig2 3 6", "let2 own kit dig", "let3 art zero" }; |
| 74 | + String[] logs = { "a1 9 2 3 1", "g1 act car", "zo4 4 7", "ab1 off key dog", "a8 act zoo" }; |
| 75 | + String[] results = new Solution().reorderLogFiles(logs); |
| 76 | + System.out.println(Arrays.toString(results)); |
| 77 | + } |
| 78 | +} |
0 commit comments