class Solution:
def printVertically(self, s: str) -> list[str]:
words = s.split()
max_len = max(len(word) for word in words)
res = []
for i in range(max_len):
line = ''
for word in words:
if i < len(word):
line += word[i]
else:
line += ' '
res.append(line.rstrip())
return res
class Solution {
public:
vector<string> printVertically(string s) {
vector<string> words;
stringstream ss(s);
string word;
while (ss >> word) words.push_back(word);
int max_len = 0;
for (auto &w : words) max_len = max(max_len, (int)w.size());
vector<string> res;
for (int i = 0; i < max_len; ++i) {
string line;
for (auto &w : words) {
if (i < w.size()) line += w[i];
else line += ' ';
}
while (!line.empty() && line.back() == ' ') line.pop_back();
res.push_back(line);
}
return res;
}
};
class Solution {
public List<String> printVertically(String s) {
String[] words = s.split(" ");
int maxLen = 0;
for (String word : words) maxLen = Math.max(maxLen, word.length());
List<String> res = new ArrayList<>();
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(' ');
}
int end = sb.length();
while (end > 0 && sb.charAt(end - 1) == ' ') end--;
res.add(sb.substring(0, end));
}
return res;
}
}
var printVertically = function(s) {
const words = s.split(' ');
const maxLen = Math.max(...words.map(w => w.length));
const res = [];
for (let i = 0; i < maxLen; ++i) {
let line = '';
for (let word of words) {
if (i < word.length) line += word[i];
else line += ' ';
}
res.push(line.replace(/\s+$/g, ''));
}
return res;
};
s
consisting of words separated by single spaces, your task is to print the words vertically. Each vertical line should be formed by taking the characters at the same index from each word. If a word is shorter than the current index, use a space character instead. Trailing spaces at the end of each vertical string should be removed. Return the result as a list of strings, each representing a vertical line.
s
into a list of words.max_len - 1
:s = "HOW ARE YOU"
["HOW", "ARE", "YOU"]
["HAY", "ORO", "WEU"]