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;
    }
}
发布了710 篇原创文章 · 获赞 13 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/105549103