Leetcode 1324. Print Words Vertically

Problem Explanation:

The problem given here is a string manipulation problem. We are provided with a string which contains multiple words separated by single spaces. The task is to return the words vertically in the same order as they appear in the string. Words are to be returned as a list of strings, with spaces filled in where necessary, but trailing spaces are not allowed. Each word would be aligned along one column, and each column would only contain one word.

Let's discuss this with the help of an Example:

Example: Suppose our input is string s = "TO BE OR NOT TO BE" Then, our output would be ["TBONTB","OEROOE"," T"]

Explanation of the Example: In the input string, we have words "TO", "BE", "OR", "NOT", "TO", "BE". If we arrange them vertically, we get: "TBONTB" "OEROOE" " T" Hence the output is a list of strings : ["TBONTB","OEROOE"," T"]

Approach to the solution:

We can solve this problem by following the below steps:

  1. Split the input string into separate words and put them in a list. Also, keep track of the length of the longest word.
  2. Iterate over the characters in the words up to the length of the longest word. During each iteration, add the corresponding character from each word to the current row-string. If a word is shorter, add a space instead.
  3. If a row-string has trailing spaces, remove them.
  4. Add each row-string (which represents a column of words) to the resulting list.

This problem basically involves string manipulation, and can be solved using these steps without the need for special algorithms or data structures.

Python Solution

1
2python
3class Solution:
4    def printVertically(self, s: str) -> List[str]:
5        words = s.split()  # split the string into separate words
6        max_len = max(len(word) for word in words)  # find the length of the longest word
7        ans = []
8        for i in range(max_len):  # iterate over the characters in the words
9            cur = ""  # start a new empty string for each row
10            for word in words:  # for each word...
11                if i < len(word):  # ... if the current index is within the length of the word...
12                    cur += word[i]  # ... add the corresponding character to the row string
13                else:  # ... otherwise add a space
14                    cur += " "
15            ans.append(cur.rstrip())  # remove trailing spaces and append the row string to the resulting list
16        return ans

Java Solution

1
2java
3import java.util.*;
4
5public class Solution {
6    public List<String> printVertically(String s) {
7        List<String> words = Arrays.asList(s.split(" "));
8        int maxLength = 0;
9        for (String word : words)
10            maxLength = Math.max(maxLength, word.length());
11        List<String> ans = new ArrayList<>();
12        for (int i = 0; i < maxLength; i++) {
13            StringBuilder row = new StringBuilder();
14            for (String word : words)
15                row.append(i < word.length() ? word.charAt(i) : ' ');
16            while (row.charAt(row.length()-1) == ' ')
17                row.deleteCharAt(row.length()-1);
18            ans.add(row.toString());
19        }
20        return ans;
21    }
22}

Javascript Solution

1
2javascript
3var printVertically = function(s) {
4    let words = s.split(' ');
5    let maxLen = Math.max(...words.map(word => word.length));
6    let ans = [];
7    for (let i = 0; i < maxLen; i++) {
8        let row = '';
9        for (let word of words) {
10            row += i < word.length ? word[i] : ' ';
11        }
12        ans.push(row.trimEnd());
13    }
14    return ans;
15};

C++ Solution

1
2c++
3class Solution {
4public:
5    vector<string> printVertically(string s) {
6        vector<string> words;
7        istringstream iss(s);
8        string token;
9        while (iss >> token) {
10            words.push_back(token);
11        }
12        size_t maxLength = 0;
13
14        for (const string& word : words)
15            maxLength = max(maxLength, word.length());
16
17        vector<string> ans;
18        for (size_t i = 0; i < maxLength; ++i) {
19            string row;
20            for (const string& word : words)
21                row += i < word.length() ? word[i] : ' ';
22            while (row.back() == ' ')
23                row.pop_back();
24            ans.push_back(row);
25        }
26
27        return ans;
28    }
29};

C# Solution

1
2csharp
3public class Solution {
4    public IList<string> PrintVertically(string s) {
5        var words = s.Split(' ');
6        var maxLength = words.Max(w => w.Length);
7        var list = new List<string>();
8        for (int i = 0; i < maxLength; i++) {
9            var current = "";
10            foreach (string word in words)
11                current += i < word.Length ? word[i] : ' ';
12            list.Add(current.TrimEnd());
13        }
14        return list;
15    }
16}

These solutions work for all test cases because they strictly follow the steps laid out in the approach to the problem. They split the input string into words, then iterate over the characters in the words (up to the length of the longest word), adding the characters to the result in a vertical orientation. If a word is too short, a space is added instead. Any trailing spaces are then removed. The time complexity for these solutions is linear, which makes them efficient even for larger inputs.The Python, Javascript, Java, C++, and C# solutions work for this problem because they correctly implement the process of breaking the string into separate words, iterating through the characters of each word in a vertical manner, and removing any trailing spaces.

  1. The Python solution splits the string into separate words, finds the length of the longest word, and then iterates through each character of the words in vertical order, removing any trailing spaces.

  2. The Javascript solution follows a similar method as the Python approach. The difference is in the removal of trailing spaces, where the 'trimEnd' function is used.

  3. In the Java solution, the string is divided into individual words, and the 'charAt' function is used to access the characters of each word. The StringBuilder object is used for efficiency, and the deletion of trailing spaces is done by checking the last character of the row string and deleting it if it's a space.

  4. The C++ solution is similar to the Java approach, but the istringstream class is used for splitting the string into individual words. The 'back' function is used to access the last character of the row string and the 'pop_back' function is used to delete it if it's a space.

  5. The C# solution closely follows the Python and Javascript approach but uses the 'TrimEnd' function to remove the trailing spaces.

In summary, these solutions provide efficient and straightforward ways to solve the problem of printing words vertically from a string. They are linear in time complexity, which means they can handle larger inputs efficiently.


Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ