937. Reorder Data in Log Files
Last updated
Last updated
time: O(nlogn), n is logs content length
space:(n)
class Solution {
public String[] reorderLogFiles(String[] logs) {
if(logs == null || logs.length == 0) return null;
Arrays.sort(logs, (a,b) -> {
String[] aStr = a.split(" ", 2); // string becomes 2 parts, [identifier, content]
String[] bStr = b.split(" ", 2);
boolean isADigit = Character.isDigit(aStr[1].charAt(0)); // check content is digit
boolean isBDigit = Character.isDigit(bStr[1].charAt(0));
if (!isADigit && !isBDigit) { // both string
if (!aStr[1].equals(bStr[1])) { // if a String != b String return their compare
return aStr[1].compareTo(bStr[1]);
} else {
return aStr[0].compareTo(bStr[0]); // a String == b String, use identifier to compare
}
} else if (isADigit && isBDigit) { // both digit, maintain original order
return 0;
} else if (!isADigit) { // -1 means a put first, so if a is char, put first
return -1;
} else {
return 1;
}
});
return logs;
}
}
/*
["identifier asdddsdsa fefwef", "identifier 1 2 3 4 4"]
letter-logs before digital
sorted lexicographically by their contents,
contents are the same, then sort them lexicographically by their identifiers.
[]
*/