Reorder Data in Log Files
给一个log文件, 里面有两种log, 一个是全是字符, 一个是全是数字. 要求排序, 全是字符的按照字符的字典序排序, 全是数字的维持不变.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class Solution { public static String[] reorderLogFiles(String[] logs) { Comparator<String> comparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { String[] s1 = o1.split(" ", 2); String[] s2 = o2.split(" ", 2); boolean isDigit1 = Character.isDigit(s1[1].charAt(0)); boolean isDigit2 = Character.isDigit(s2[1].charAt(0)); if (!isDigit1 && !isDigit2) { // if both string are not number if (s1[1].compareTo(s2[1]) != 0) { // if content is diff return s1[1].compareTo(s2[1]); } else { // compare the id return s1[0].compareTo(s2[0]); } } else { if (isDigit1 && isDigit2) { return 0; } else if (isDigit1){ return 1; } else{ return -1; } } } }; Arrays.sort(logs, comparator); return logs; } } |