Skip to content

1324. Print Words Vertically 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
 public:
  vector<string> printVertically(string s) {
    vector<string> ans;
    vector<string> words = split(s);
    size_t maxLength = 0;

    for (const string& word : words)
      maxLength = max(maxLength, word.length());

    for (size_t i = 0; i < maxLength; ++i) {
      string row;
      for (const string& word : words)
        row += i < word.length() ? word[i] : ' ';
      while (row.back() == ' ')
        row.pop_back();
      ans.push_back(row);
    }

    return ans;
  }

 private:
  vector<string> split(const string& s) {
    vector<string> words;
    istringstream iss(s);
    for (string token; iss >> token;)
      words.push_back(token);
    return words;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public List<String> printVertically(String s) {
    List<String> ans = new ArrayList<>();
    String[] words = s.split(" ");
    int maxLength = 0;

    for (final String word : words)
      maxLength = Math.max(maxLength, word.length());

    for (int i = 0; i < maxLength; ++i) {
      StringBuilder sb = new StringBuilder();
      for (final String word : words)
        sb.append(i < word.length() ? word.charAt(i) : ' ');
      while (sb.charAt(sb.length() - 1) == ' ')
        sb.deleteCharAt(sb.length() - 1);
      ans.add(sb.toString());
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def printVertically(self, s: str) -> list[str]:
    ans = []
    words = s.split()
    maxLength = max(len(word) for word in words)

    for i in range(maxLength):
      row = []
      for word in words:
        row.append(word[i] if i < len(word) else ' ')
      ans.append(''.join(row).rstrip())

    return ans