|
| 1 | +/** |
| 2 | + * 937. Reorder Data in Log Files |
| 3 | + * https://leetcode.com/problems/reorder-data-in-log-files/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an array of logs. Each log is a space-delimited string of words, |
| 7 | + * where the first word is the identifier. |
| 8 | + * |
| 9 | + * There are two types of logs: |
| 10 | + * - Letter-logs: All words (except the identifier) consist of lowercase English |
| 11 | + * letters. |
| 12 | + * - Digit-logs: All words (except the identifier) consist of digits. |
| 13 | + * |
| 14 | + * Reorder these logs so that: |
| 15 | + * 1. The letter-logs come before all digit-logs. |
| 16 | + * 2. The letter-logs are sorted lexicographically by their contents. If their |
| 17 | + * contents are the same, then sort them lexicographically by their identifiers. |
| 18 | + * 3. The digit-logs maintain their relative ordering. |
| 19 | + * |
| 20 | + * Return the final order of the logs. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {string[]} logs |
| 25 | + * @return {string[]} |
| 26 | + */ |
| 27 | +var reorderLogFiles = function(logs) { |
| 28 | + const split = logs.map(l => l.split(' ')); |
| 29 | + const sortedA = split.filter(l => isNaN(parseInt(l[1], 10))).sort((a, b) => { |
| 30 | + return a[1] !== b[1] |
| 31 | + ? a[1].localeCompare(b[1]) : a[2] !== b[2] |
| 32 | + ? a[2].localeCompare(b[2]) : a.length === b.length |
| 33 | + ? a[0].localeCompare(b[0]) : a.length - b.length; |
| 34 | + }).map(l => l.join(' ')); |
| 35 | + const sortedB = split.filter(l => !isNaN(parseInt(l[1], 10))) |
| 36 | + .sort((a, b) => b - a) |
| 37 | + .map(l => l.join(' ')); |
| 38 | + |
| 39 | + return [...sortedA, ...sortedB]; |
| 40 | +}; |
0 commit comments