Print Words Vertically Problem
Description
LeetCode Problem 1324.
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.
Example 1:
Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically.
"HAY"
"ORO"
"WEU"
Example 2:
Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE"," T"]
Explanation: Trailing spaces is not allowed.
"TBONTB"
"OEROOE"
" T"
Example 3:
Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]
Constraints:
1 <= s.length <= 200scontains only upper case English letters.- It's guaranteed that there is only one space between 2 words.
Solution
Approach: Read the Words Column by Column
Split s into words. Word j becomes column j of the answer, so row i of the answer is made of the i-th letter of every word, from left to right. The number of rows is the length of the longest word.
When a word is shorter than i + 1 letters, its column has no letter in row i, and we put a space there so the letters of the following words stay in their own columns (see " T" in Example 2). Only at the end of a row are spaces not allowed, so after building each row we strip its trailing spaces.
The last row always ends with a letter of a longest word, so no row is left empty.
Complexity: O(w·h) time and space, where w is the number of words and h the length of the longest word. Both are bounded by the length of s.
class Solution:
def printVertically(self, s: str) -> List[str]:
words = s.split()
height = max(len(w) for w in words)
rows = []
for i in range(height):
# The i-th letter of every word, with a space for words that are too short.
row = "".join(w[i] if i < len(w) else " " for w in words)
rows.append(row.rstrip()) # no trailing spaces
return rows