头像

带翅膀的猫

时光荏苒,我们一直都在

《LeetCode刷题(Easy Rank):937. Reorder Log Files》

 1月前  •   LeetCode  •     •   33  •   0

Question:

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:

示例Input: ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]

Solution:

JAVAclass Solution {
    public String[] reorderLogFiles(String[] logs) {
        Queue<String> queue = new ArrayDeque<>();
        String[] strs = new String[logs.length];
        int i=0;
        for(String log:logs){
            char ch = log.charAt(log.indexOf(' ')+1);
            if(ch>='0'&&ch<='9'){
                queue.add(log);continue;//数字日志先放入队列中
            }
            strs[i]=log;i++;//将字符日志放入str[]中
        }
        sort(strs,i);//对字符日志按照题目要求进行排序
        while(!queue.isEmpty()){//直接将数字日志添加到str[]中
            strs[i] = queue.poll();
            i++;
        }
        return strs;
    }
    private void sort(String[] strs,int n){
        for(int i=0;i<n-1;i++){
            for(int j=i+1;j<n;j++){
                if(compareString(strs[i],strs[j])>0){
                    String temp = strs[i];
                    strs[i] = strs[j];
                    strs[j] = temp;
                }
            }
        }
    }
    private int compareString(String str1,String str2){
        str1 = str1.substring(str1.indexOf(' '));
        str2 = str2.substring(str2.indexOf(' '));
        return str1.compareTo(str2);
    }
}

 

上一篇:
没有了,已经是最新文章啦

 评论


 已有0条评论

    还没有任何评论,你来说两句吧!