【字符串】B040_LC_豎直打印單詞(模擬 + 思維)

一、Problem

Given a string s. Return all the words vertically in the same order in which they appear in s.

Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).

Each word would be put on only one column and that in one column there will be only one word.

Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE","   T"]
Explanation: Trailing spaces is not allowed. 
"TBONTB"
"OEROOE"
"   T"

二、Solution

方法一:模擬 + 思維

  • 使用變量 col 記錄當前遍歷到的列,因爲我們是按照列遍歷全部字符串的。
  • 如果 col 小於當前遍歷字符的長度 len_i,那麼可以將當前字符串的當前字符添加到 sb 中,否則只能添加空格 ' '
  • 注意,如果字符串數組 ss 中間又字符串長度突出,那麼 sb 的末尾就會有尾隨空格 ' ',我們需要將其刪除。
class Solution {
    public List<String> printVertically(String S) {
        String[] ss = S.split(" ");
        List<String> res = new LinkedList<>();
        if (ss.length == 0)
            return res;
        int col = 0, max = 0;
        for (String s : ss) {  
            max = Math.max(max, s.length());    
        }
        while (col < max) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ss.length; i++) {
                if (col < ss[i].length())
                    sb.append(ss[i].charAt(col));
                else if (col >= ss[i].length())
                    sb.append(' ');
            }
            while (sb.charAt(sb.length()-1) == ' ')
                sb.deleteCharAt(sb.length()-1);
            res.add(sb.toString());
            col++;
        }
        return res;
    }
}

複雜度分析

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