Leetcode 1324.竖直打印单词(Print Words Vertically)

Leetcode 1324.竖直打印单词

1 题目描述(Leetcode题目链接)

  给你一个字符串 s。请你按照单词在 s 中的出现顺序将它们全部竖直返回。单词应该以字符串列表的形式返回,必要时用空格补位,但输出尾部的空格需要删除(不允许尾随空格)。每个单词只能放在一列上,每一列中也只能有一个单词。

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

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

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

提示:

  • 1 <= s.length <= 200
  • s 仅含大写英文字母。
  • 题目数据保证两个单词之间只有一个空格。

2 题解

  先将输入按空格切分成列表,然后找到最长单字长度,以这个长度为列构造新单词,根据情况补充空格,最后将构造好的单词的后面所有空格都去掉。

class Solution:
    def printVertically(self, s: str) -> List[str]:
        s = s.split()
        max_length = 0
        for word in s:
            max_length = max(len(word), max_length)
        target = ""; retv = []
        for i in range(max_length):
            for word in s:
                if i < len(word):
                    target += word[i]
                else:
                    target += " "
            retv.append(target.rstrip())
            target = ""
        return retv

你可能感兴趣的:(Leetcode)