This is a problem which check whether you know how to user Arrays.sort().
Time complexity: O(m*n*log(m+n)
Solution 1: Using comparator
class Solution { public String[] reorderLogFiles(String[] logs) { Arrays.sort(logs, new MyComparator()); return logs; } public class MyComparator implements Comparator<String>{ public int compare(String log1, String log2){ int idx1 = log1.indexOf(" ") + 1; int idx2 = log2.indexOf(" ") + 1; boolean isChar1 = Character.isAlphabetic(log1.charAt(idx1)); boolean isChar2 = Character.isAlphabetic(log2.charAt(idx2)); if(isChar1 && isChar2){ String tail1 = log1.substring(idx1); String tail2 = log2.substring(idx2); int temp = tail1.compareTo(tail2); if(temp != 0) return temp; else return log1.compareTo(log2); }else if(isChar1) return -1; else if(isChar2) return 1; else return 0; } } }
Solution 2: Using Lamda
class Solution { public String[] reorderLogFiles(String[] logs) { Arrays.sort(logs, (log1, log2) -> { int idx1 = log1.indexOf(" ")+1; int idx2 = log2.indexOf(" ")+1; boolean isChar1 = Character.isAlphabetic(log1.charAt(idx1)); boolean isChar2 = Character.isAlphabetic(log2.charAt(idx2)); if(isChar1 && isChar2) { String tail1 = log1.substring(idx1); String tail2 = log2.substring(idx2); if(tail1.equals(tail2)){ return log1.compareTo(log2); }else return tail1.compareTo(tail2); } else if(isChar1) { return -1; } else if(isChar2) { return 1; }else return 0; }); return logs; } }