Friday, January 4, 2019

937. Reorder Log Files

Version #2 Compare digits and letters together
class Solution {
    public String[] reorderLogFiles(String[] logs) {
Arrays.sort(logs, (a, b) -> {
String[] aa = a.split(" ", 2);
String[] bb = b.split(" ", 2);
boolean aIsDigit = aa[1].matches("[0-9\\s]+");
boolean bIsDigit = bb[1].matches("[0-9\\s]+");
if (!aIsDigit && !bIsDigit) {
if (aa[1].equals(bb[1])) {
return aa[0].compareTo(bb[0]);
}
return aa[1].compareTo(bb[1]);
}
return (aIsDigit ? 1 : 0) - (bIsDigit ? 1 : 0);
});
return logs;
}
}

Version #1 Bad
3.05 %
class Solution {
    public String[] reorderLogFiles(String[] logs) {
List<String> letterLogs = new ArrayList<>();
List<String> digitLogs = new ArrayList<>();
for (String log : logs) {
int spacer = log.indexOf(" ");
if (spacer == -1 || log.length() <= spacer + 1) continue; //invalid
String str = log.substring(spacer + 1);
if (str.matches("[0-9\\s]+")) {
digitLogs.add(log);
} else {
letterLogs.add(log);
}
}
Collections.sort(letterLogs, (a, b) -> {
String[] aa = a.split(" ", 2);
String[] bb = b.split(" ", 2);
if (aa[1].equals(bb[1])) {
return aa[0].compareTo(bb[0]);
}
return aa[1].compareTo(bb[1]);
});
letterLogs.addAll(digitLogs);
return letterLogs.toArray(new String[letterLogs.size()]);
}
}

No comments:

Post a Comment