5316. vertical print word (print-words-vertically)

Vertical print word (print-words-vertically)

Give you a string s. Please follow the words in the sorder that they appear in all of them return to the vertical.
Word should be returned as a list of strings, with spaces to fill the seats, but the output trailing spaces, if necessary, need to remove (trailing spaces are not allowed).
Each word can only be placed on one, each column can have only one word.

Example 1:

输入:s = "HOW ARE YOU"
输出:["HAY","ORO","WEU"]
解释:每个单词都应该竖直打印。 
 "HAY"
 "ORO"
 "WEU"

Example 2:

输入:s = "TO BE OR NOT TO BE"
输出:["TBONTB","OEROOE","   T"]
解释:题目允许使用空格补位,但不允许输出末尾出现空格。
"TBONTB"
"OEROOE"
"   T"

Example 3:

输入:s = "CONTEST IS COMING"
输出:["CIC","OSO","N M","T I","E N","S G","T"]

Tip:
1 <= s.length <= 200
scontains only capital letters.
Topic data to ensure that only one space between two words.

Code and ideas

The length of the longest first find all the words in the word that is assumed to maxLen;
column traversing [0, maxLen), then for each word, each word corresponding to the fetched character column, the column when the current exceeds the word length, replace with spaces;
which, subject to the removal of said trailing spaces (note, not trailing spaces, not directly trim), therefore, each processed on a trailing space to handle it.
Come from

    // 删除尾随空格
    private String removeSuffixSpaces(String str) {
        StringBuilder sb = new StringBuilder();
        boolean begin = false;
        for (int i = str.length() - 1; i >= 0; i--) {
            if (str.charAt(i) != ' ') {
                begin = true;
            }

            if (begin) {
                sb.append(str.charAt(i));
            }
        }

        return sb.reverse().toString();
    }

    public List<String> printVertically(String s) {
        String[] str = s.split(" ");
        int wordLen = str.length;

        int maxLen = 0;
        for (String word : str) {
            maxLen = Math.max(maxLen, word.length());
        }

        List<String> ansList = new ArrayList<>();
        for (int j = 0; j < maxLen ;j++) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < wordLen; i++) {
                if (str[i].length() <= j) {
                    sb.append(' ');
                } else {
                    sb.append(str[i].charAt(j));
                }
            }

            ansList.add(removeSuffixSpaces(sb.toString()));
        }

        return ansList;
    }

Reference material

Vertical print word

Published 154 original articles · won praise 47 · Views 230,000 +

Guess you like

Origin blog.csdn.net/e891377/article/details/104056810