【字符串】B038_LC_重新排列句子中的單詞(模擬 / TreeMap)

一、Problem

Given a sentence text (A sentence is a string of space-separated words) in the following format:

  • First letter is in upper case.
  • Each word in text are separated by a single space.

Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.

Return the new text following the format shown above.

Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.

二、Solution

方法一:模擬

…細節頗多,這是比賽時寫的,不過看到還有人寫得更簡潔。

class Solution {
    public String arrangeWords(String text) {
        String ss[] = text.split(" ");
        String fir = ss[0];
        Arrays.sort(ss, (e1, e2) -> {
            return e1.length() - e2.length();
        });
        int idx = 0;
        for (int i = 0; i < ss.length; i++) {
            if (fir.equals(ss[i]) && i != 0){
                idx = i;
                break;
            }
        }
        if (ss.length == 0)
            return "";
        StringBuilder res = new StringBuilder();
        res.append(Character.toUpperCase(ss[0].charAt(0)));
        res.append(ss[0].substring(1));
        
        for (int i = 1; i < ss.length; i++) {
            res.append(" ");
            if (i == idx) {
                res.append(Character.toLowerCase(ss[i].charAt(0)));
                res.append(ss[i].substring(1));
                continue;
            }
            res.append(ss[i]);
        }
        return res.toString();
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)

方法二:TreeMap

比我的代碼要簡單的地方在於:

  • 利用了 TreeMap 的自動排序,不用像我那樣對字符串數組排序,然後排完序還要判斷首個單詞是否移動了位置。
class Solution {
    public String arrangeWords(String text) {
        Map<Integer, List<String>> m = new TreeMap<>();
        for (String s : text.split(" ")){
            m.computeIfAbsent(s.length(), k -> new ArrayList<>()).add(s);
        }
        StringBuilder sb = new StringBuilder();
        for (int k : m.keySet())
        for (String s : m.get(k)) {
            sb.append(s.toLowerCase());
            sb.append(" ");
        }
        sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
        return sb.toString().substring(0, sb.length()-1);
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章