LeetCode 题解工作台

竖直打印单词

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

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·string

bolt

答案摘要

我们先将字符串 按空格分割成单词数组 ,然后遍历单词数组,找出最长的单词长度 。 接下来我们从第 到第 个字符,分别从单词数组中取出对应的字符,如果当前单词长度不足,则用空格补齐,放到一个字符串 中。最后将 去掉末尾的空格,加入答案数组中即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

 

示例 1:

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

示例 2:

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

示例 3:

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

 

提示:

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

解题思路

方法一:模拟

我们先将字符串 ss 按空格分割成单词数组 wordswords,然后遍历单词数组,找出最长的单词长度 nn

接下来我们从第 11 到第 nn 个字符,分别从单词数组中取出对应的字符,如果当前单词长度不足,则用空格补齐,放到一个字符串 tt 中。最后将 tt 去掉末尾的空格,加入答案数组中即可。

时间复杂度 O(m)O(m),空间复杂度 O(m)O(m)。其中 mm 为字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def printVertically(self, s: str) -> List[str]:
        words = s.split()
        n = max(len(w) for w in words)
        ans = []
        for j in range(n):
            t = [w[j] if j < len(w) else ' ' for w in words]
            while t[-1] == ' ':
                t.pop()
            ans.append(''.join(t))
        return ans
speed

复杂度分析

指标
时间complexity is O(n * m), where n is the number of words and m is the length of the longest word, because each character in each word is visited once. Space complexity is also O(n * m) due to storing vertical strings in the result array.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Are you considering varying word lengths for column generation?

  • question_mark

    How do you handle trailing spaces when shorter words end before longer ones?

  • question_mark

    Can you simulate the vertical printing without using extra nested arrays?

warning

常见陷阱

外企场景
  • error

    Not trimming trailing spaces, resulting in incorrect output format.

  • error

    Assuming all words have equal length, causing index out-of-range errors.

  • error

    Appending characters in the wrong order and losing the original word sequence.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return words rotated diagonally instead of strictly vertical columns.

  • arrow_right_alt

    Handle lowercase and mixed-case letters while preserving original formatting.

  • arrow_right_alt

    Support multiple spaces between words and preserve spacing alignment in output.

help

常见问题

外企场景

竖直打印单词题解:数组·string | LeetCode #1324 中等