Created
November 15, 2019 04:09
-
-
Save forkercat/3dfc5bda886acdd030848599b3b9faa8 to your computer and use it in GitHub Desktop.
937. Reorder Data in Log Files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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