Reorder Data in Log Files

You have an array of logs.  Each log is a space delimited string of words.

For each log, the first word in each log is an alphanumeric identifier.  Then, either:

  • Each word after the identifier will consist only of lowercase letters, or;
  • Each word after the identifier will consist only of digits.

We will call these two varieties of logs letter-logs and digit-logs.  It is guaranteed that each log has at least one word after its identifier.

Reorder the logs so that all of the letter-logs come before any digit-log.  The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties.  The digit-logs should be put in their original order.

Return the final order of the logs.

Example 1:

Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]

思路:就是寫個comparator,注意細節;如果都是數字的話,順序不變,return 0, 0 是原地不動;如果一個是字母,一個是數字,則字母在前面,return 1 倒序, 否則return - 1 升序;

class Solution {
    private class logComparator implements Comparator<String> {
        @Override
        public int compare(String a, String b) {
            String[] asplit = a.split(" ", 2); // 2 代表空格只用最多一次;
            String[] bsplit = b.split(" ", 2);
            
            boolean aisdigit = Character.isDigit(asplit[1].charAt(0));
            boolean bisdigit = Character.isDigit(bsplit[1].charAt(0));
            
            if(!aisdigit && !bisdigit) {
                if(asplit[1].equals(bsplit[1])) {
                    return asplit[0].compareTo(bsplit[0]);
                } else {
                    return asplit[1].compareTo(bsplit[1]);
                }
            } else if( aisdigit && bisdigit) {
                return 0; // 順序不變;
            } else if( aisdigit && !bisdigit) {
                return 1; // 倒序;把後面的放前面;
            } else  {
                // !aisdigit && bisdigit
                return -1; // 順序;
            }
        }
    }
    
    public String[] reorderLogFiles(String[] logs) {
        Arrays.sort(logs, new logComparator());
        return logs;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章