Java教程

937. Reorder Data in Log Files

本文主要是介绍937. Reorder Data in Log Files,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

This is a problem which check whether you know how to user Arrays.sort().

Time complexity: O(m*n*log(m+n)

Solution 1: Using comparator

class Solution {
    public String[] reorderLogFiles(String[] logs) {
        Arrays.sort(logs, new MyComparator());
        return logs;        
    }
    
    public class MyComparator implements Comparator<String>{
        public int compare(String log1, String log2){
            int idx1 = log1.indexOf(" ") + 1;
            int idx2 = log2.indexOf(" ") + 1;

            boolean isChar1 = Character.isAlphabetic(log1.charAt(idx1));
            boolean isChar2 = Character.isAlphabetic(log2.charAt(idx2));

            if(isChar1 && isChar2){
                String tail1 = log1.substring(idx1);
                String tail2 = log2.substring(idx2);
                int temp = tail1.compareTo(tail2);
                if(temp != 0) 
                    return temp;
                else 
                    return log1.compareTo(log2);
            }else if(isChar1) 
                return -1;
            else if(isChar2) 
                return 1;
            else 
                return 0;
        }
    }
}

Solution 2: Using Lamda

class Solution {
    public String[] reorderLogFiles(String[] logs) {
        Arrays.sort(logs, (log1, log2) -> {
            int idx1 = log1.indexOf(" ")+1;
            int idx2 = log2.indexOf(" ")+1;
            
            boolean isChar1 = Character.isAlphabetic(log1.charAt(idx1));
            boolean isChar2 = Character.isAlphabetic(log2.charAt(idx2));
            
            if(isChar1 && isChar2) {
                String tail1 = log1.substring(idx1);
                String tail2 = log2.substring(idx2);
                if(tail1.equals(tail2)){
                    return log1.compareTo(log2);
                }else
                    return tail1.compareTo(tail2);
            } else if(isChar1) { 
                return -1;
            } else if(isChar2) {
                return 1;
            }else
                return 0;
        });
        return logs;
    }
}

 

这篇关于937. Reorder Data in Log Files的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!