zoukankan      html  css  js  c++  java
  • LeetCode 937. Reorder Data in Log Files

    题目标签:String

      写一个comparator,先分离identifier 和 content,然后分情况比较:

        1. 两个 log 都是 letter logs,先比较 content,如果一样content 再比较 identifiers

        2. 一个letter log, 一个 digit log

        3. 两个都是 digit logs

      具体看code。

    Java Solution: 

    Runtime:  14ms, faster than 12.57% 

    Memory Usage: 46.5MB, less than 5.13%

    完成日期:01/26/2021

    关键点:override compare

    class Solution {
        public String[] reorderLogFiles(String[] logs) {
    
            Comparator<String> myComp = new Comparator<String>() {
                @Override
                public int compare(String log1, String log2) {
                    // split each log into two parts: <identifier, content>
                    String[] split1 = log1.split(" ", 2);
                    String[] split2 = log2.split(" ", 2);
    
                    boolean isDigit1 = Character.isDigit(split1[1].charAt(0));
                    boolean isDigit2 = Character.isDigit(split2[1].charAt(0));
    
                    // case 1). both logs are letter-logs
                    if (!isDigit1 && !isDigit2) {
                        // first compare the content
                        int cmp = split1[1].compareTo(split2[1]);
                        if (cmp != 0)
                            return cmp;
                        // logs of same content, compare the identifiers
                        return split1[0].compareTo(split2[0]);
                    }
    
                    // case 2). one of logs is digit-log
                    if (!isDigit1 && isDigit2)
                        // the letter-log comes before digit-logs
                        return -1;
                    else if (isDigit1 && !isDigit2)
                        return 1;
                    else
                        // case 3). both logs are digit-log
                        return 0;
                }
            };
    
            Arrays.sort(logs, myComp);
            return logs;
        }
    }

    参考资料:https://leetcode.com/problems/reorder-data-in-log-files/solution/

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    团队贡献分
    《一个程序猿的生命周期》读后感
    阅读课本13-17章
    第三阶段冲刺(进度反应)
    阅读<构建之法>10、11、12章
    典型用户与场景描述
    第一阶段小组互评及反馈
    第一阶段总结及第二阶段开始会议
    spring冲刺阶段之团队工作总结
    alpha阶段总结 (第一阶段冲刺成果)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/14333934.html
Copyright © 2011-2022 走看看