leetcode (Reorder Log Files)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85243608

Title:见代码注释   937

Difficulty:Easy

原题leetcode地址: https://leetcode.com/problems/reorder-log-files/

1.   见代码注释

时间复杂度:O(n^2),嵌套for循环,最长为letter字符串的个数的平方。

空间复杂度:O(n),申请tmp长度为字符串数组的长度的字符串数组。

    /**
     * 计算出总共有多少letter的字符串
     * 将digit的字符串依次存放在最后,将letter的字符串存放在最前
     * 将前面存放的letter的字符串排序
     * @param logs
     * @return
     */
    public static String[] reorderLogFiles(String[] logs) {

        String tmp[] = new String[logs.length];
        int letterCount = 0;

        for (String log : logs) {
            String strLog[] = log.split(" ", 2);
            if (strLog[1].charAt(0) >='a' && strLog[1].charAt(0) <= 'z') {
                letterCount++;
            }
        }

        int index = 0;
        int count = letterCount;
        for (int i = 0; i < logs.length; i++) {
            String strLog[] = logs[i].split(" ", 2);
            if (strLog[1].charAt(0) >= '0' && strLog[1].charAt(0) <= '9') {
                tmp[letterCount++] = logs[i];
            }
            else {
                tmp[index++] = logs[i];
            }
        }

        for (int i = 0; i < count; i++) {
            for (int j = i; j < count; j++) {
                if (tmp[i].split(" ", 2)[1].compareTo(tmp[j].split(" ", 2)[1]) > 0) {
                    String temp = tmp[i];
                    tmp[i] = tmp[j];
                    tmp[j] = temp;
                }
            }
        }

        for (int i = 0; i < logs.length; i++) {
            logs[i] = tmp[i];
        }

        return logs;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85243608
今日推荐