|
| 1 | +// https://leetcode.com/problems/reorder-data-in-log-files/ |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "sort" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +func reorderLogFiles(logs []string) []string { |
| 11 | + |
| 12 | + words := make([]string, 0, len(logs)) |
| 13 | + digits := make([]string, 0, 16) |
| 14 | + |
| 15 | + for _, lw := range logs { |
| 16 | + if isDigit(rec(lw)[0]) { |
| 17 | + digits = append(digits, lw) |
| 18 | + } else { |
| 19 | + words = append(words, lw) |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + sort.Slice(words, func(i, j int) bool { |
| 24 | + recI := rec(words[i]) |
| 25 | + recJ := rec(words[j]) |
| 26 | + if recI == recJ { |
| 27 | + return words[i] < words[j] |
| 28 | + } |
| 29 | + return recI < recJ |
| 30 | + }) |
| 31 | + |
| 32 | + return append(words, digits...) |
| 33 | +} |
| 34 | + |
| 35 | +func rec(log string) string { |
| 36 | + return string([]byte(log)[strings.Index(log, " ")+1:]) |
| 37 | +} |
| 38 | + |
| 39 | +func isDigit(c byte) bool { |
| 40 | + return c >= '0' && c <= '9' |
| 41 | +} |
| 42 | + |
| 43 | +/* |
| 44 | +["8 fj dzz k", "5r 446 6 3", "63 gu psub", "5 ba iedrz", "6s 87979 5", "3r 587 01", "jc 3480612", "bb wsrd kp", "b aq cojj", "r5 6316 71"] |
| 45 | +["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo","a2 act car"] |
| 46 | +["1 n u", "r 527", "j 893", "6 14", "6 82"] |
| 47 | +["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] |
| 48 | +[] |
| 49 | +["1 n u"] |
| 50 | +["j 893", "6 14"] |
| 51 | +*/ |
0 commit comments