LeetCode 题解工作台
竖直打印单词
给你一个字符串 s 。请你按照单词在 s 中的出现顺序将它们全部竖直返回。 单词应该以字符串列表的形式返回,必要时用空格补位,但输出尾部的空格需要删除(不允许尾随空格)。 每个单词只能放在一列上,每一列中也只能有一个单词。 示例 1: 输入: s = "HOW ARE YOU" 输出: ["HAY"…
3
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数组·string
答案摘要
我们先将字符串 按空格分割成单词数组 ,然后遍历单词数组,找出最长的单词长度 。 接下来我们从第 到第 个字符,分别从单词数组中取出对应的字符,如果当前单词长度不足,则用空格补齐,放到一个字符串 中。最后将 去掉末尾的空格,加入答案数组中即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个字符串 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 <= 200s仅含大写英文字母。- 题目数据保证两个单词之间只有一个空格。
解题思路
方法一:模拟
我们先将字符串 按空格分割成单词数组 ,然后遍历单词数组,找出最长的单词长度 。
接下来我们从第 到第 个字符,分别从单词数组中取出对应的字符,如果当前单词长度不足,则用空格补齐,放到一个字符串 中。最后将 去掉末尾的空格,加入答案数组中即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.