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"]

Idea: write a comparator and pay attention to the details; if they are all numbers, the order is unchanged, return 0, 0 is unchanged; if one is a letter and one is a number, the letter is in front, return 1 is in reverse order, otherwise return -1 ascending order;

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;
    }
}

 

Published 710 original articles · Like 13 · Visits 190,000+

Guess you like

Origin blog.csdn.net/u013325815/article/details/105549103