Print Words Vertically

Solution For Print Words Vertically

Problem statement:

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.

Solution:

The approach to this problem can be as follows:

  1. Create a list of strings to store each word vertically.
  2. Split the given string s into individual words.
  3. Find the maximum length of the words.
  4. Traverse each character of each word and append it to the corresponding string in the list.
  5. Add spaces to the end of the string if the length of the word is less than the maximum length.

Code:

Here is the Python 3 solution for the problem:

“`
class Solution:
def printVertically(self, s: str) -> List[str]:

    # split the string into individual words
    words = s.split()

    # find the maximum length of the words
    max_length = max(len(word) for word in words)

    # create a list of strings to store each word vertically
    result = [''] * max_length

    # traverse each character of each word and append it to the corresponding string in the list
    for word in words:
        for i, c in enumerate(word):
            result[i] += c

    # add spaces to the end of the string if the length of the word is less than the maximum length
    for i in range(max_length):
        result[i] += ' ' * (max_length - len(result[i]))

    # remove trailing spaces
    result = [word.rstrip() for word in result]

    return result

“`

Time complexity:

The time complexity of the given solution is O(n*m), where n is the number of words in the input string and m is the maximum length of the words.

Space complexity:

The space complexity of the given solution is O(m), where m is the maximum length of the words. This is because we are storing each character of each word vertically in a list of strings.

Step by Step Implementation For Print Words Vertically

public List printVertically(String s) {
        List res = new ArrayList<>();
        if (s == null || s.length() == 0) {
            return res;
        }
        String[] words = s.split(" ");
        int maxLen = 0;
        for (String word : words) {
            maxLen = Math.max(maxLen, word.length());
        }
        for (int i = 0; i < maxLen; i++) {
            StringBuilder sb = new StringBuilder();
            for (String word : words) {
                if (i < word.length()) {
                    sb.append(word.charAt(i));
                } else {
                    sb.append(" ");
                }
            }
            res.add(sb.toString());
        }
        return res;
    }
def print_words_vertically(s):
    # your code goes here
    return
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 a new line.

/**
 * @param {string} s
 * @return {string[]}
 */
var printVertically = function(s) {
    // your code here
};
#include  
#include  
#include  

using namespace std; 

vector printWordsVertically(string s) 
{ 
    // result vector 
    vector res; 
  
    // stores current word 
    string curr = ""; 
  
    // do for each character in the string 
    for (int i = 0; i < s.length(); i++) { 
  
        // if character is not space 
        // then append this character to 
        // the current word 
        if (s[i] != ' ') 
            curr += s[i]; 
  
        // else store this word in the result 
        // vector and make current word as empty 
        else { 
            res.push_back(curr); 
            curr = ""; 
        } 
    } 
  
    // push the last word 
    res.push_back(curr); 
  
    return res; 
} 
  
// Driver code 
int main() 
{ 
    string s = "HOW ARE YOU"; 
    vector res = printWordsVertically(s); 
  
    for (string str : res) 
        cout << str << endl; 
  
    return 0; 
}
using System; 
using System.Collections.Generic; 

public class Solution { 

// Function to print words vertically 
static void printVertically(string s) 
{ 

// Splitting the string by spaces 
// and storing it in a string array 
string[] arr = s.Split(' '); 

// Finding the length of the longest string 
// in the array 
int len = 0; 
foreach (string str in arr) 
{ 
if (str.Length > len) 
{ 
len = str.Length; 
} 
} 

// Printing the strings vertically 
for (int i = 0; i < len; i++) 
{ 
foreach (string str in arr) 
{ 

// For the strings with less length, 
// we are printing spaces 
if (i >= str.Length) 
{ 
Console.Write(" "); 
} 
else
{ 

// Otherwise, printing the characters 
// of the string 
Console.Write(str[i]); 
} 
} 

// Adding a new line after printing 
// a row to print the next row from 
// the next iteration 
Console.WriteLine(); 
} 
} 
}
Scroll to Top

Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]