public class LogSorting {
/*
* 1380. Log Sorting
*
* Given a list of string logs, in which each element representing a log. Each
* log can be separated into two parts by the first space. The first part is the
* ID of the log, while the second part is the content of the log. (The content
* may contain spaces as well.) The content is composed of only letters and
* spaces, or only numbers and spaces.
*
* Now you need to sort logs by following rules:
*
* Logs whose content is letter should be ahead of logs whose content is number.
* Logs whose content is letter should be sorted by their content in
* lexicographic order. And when two logs have same content, sort them by ID in
* lexicographic order. Logs whose content is number should be in their input
* order. Example Example 1:
*
* Input: logs = [ "zo4 4 7", "a100 Act zoo", "a1 9 2 3 1", "g9 act car" ]
* Output: [ "a100 Act zoo", "g9 act car", "zo4 4 7", "a1 9 2 3 1" ]
* Explanation: "Act zoo" < "act car", so the output is as above. Example 2:
*
* Input: logs = [ "zo4 4 7", "a100 Actzoo", "a100 Act zoo", "Tac Bctzoo",
* "Tab Bctzoo", "g9 act car" ] Output: [ "a100 Act zoo", "a100 Actzoo",
* "Tab Bctzoo", "Tac Bctzoo", "g9 act car", "zo4 4 7" ] Explanation: Because
* "Bctzoo" == "Bctzoo", the comparison "Tab" and "Tac" have "Tab" < Tac ", so"
* Tab Bctzoo "< Tac Bctzoo". Because ' '<'z', so "A100 Act zoo" < A100 Actzoo".
* Notice The total number of logs will not exceed 5000 The length of each log
* will not exceed 100 Each log's ID is unique.
*/
/**
* @param logs: the logs
* @return: the log after sorting
*/
class MyComparator implements Comparator<String> {
public int compare(String s1, String s2) {
int t1 = s1.indexOf(' ');
int t2 = s2.indexOf(' ');
String ID1 = s1.substring(0, t1);
String ID2 = s2.substring(0, t2);
String body1 = s1.substring(t1);
String body2 = s2.substring(t2);
if (body1.equals(body2)) {
return ID1.compareTo(ID2);
} else {
return body1.compareTo(body2);
}
}
}
public String[] logSort(String[] logs) {
// Write your code here
int m = logs.length;
String[] ans = new String[m];
List<String> list = new ArrayList<>();
int idx = m - 1;
for (int i = m - 1; i >= 0; i--) {
int tmp = logs[i].indexOf(' ');
String body = logs[i].substring(tmp + 1);
if (Character.isDigit(body.charAt(0))) {
ans[idx--] = logs[i];
} else {
list.add(logs[i]);
}
}
Collections.sort(list, new MyComparator());
idx = 0;
for (String item : list) {
ans[idx++] = item;
}
return ans;
}
}