Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
937. Reorder Data in Log Files
class Solution {
public String[] reorderLogFiles(String[] logs) {
if (logs == null) {
return null;
}
int n = logs.length;
Map<String, String[]> map = new HashMap<>();
for (String log : logs) {
map.put(log, log.split(" ", 2)); // only consider the first word
}
// sorting
Arrays.sort(logs, (s1, s2) -> {
String[] log1 = map.get(s1);
String[] log2 = map.get(s2);
int type1 = Character.isDigit(log1[1].charAt(0)) ? 0 : 1; // 0 digit, 1 letter
int type2 = Character.isDigit(log2[1].charAt(0)) ? 0 : 1;
if (type1 == 0 && type2 == 1) {
return 1;
}
else if (type1 == 1 && type2 == 0) {
return -1;
}
else if (type1 == 0 && type2 == 0) { // both are digits
return 0;
}
else { // both are letters
int cmp = log1[1].compareTo(log2[1]);
if (cmp == 0) return log1[0].compareTo(log2[0]); // identifier
else return cmp;
}
});
return logs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment