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.
We can treat the words as columns and build each vertical word by iterating over each character index. Pad with spaces as needed, and strip trailing spaces at the end.
For each character index up to the longest word, build a string by taking the character at that index from each word (or a space if the word is too short).
import java.util.*;
classSolution {
public List<String>printVertically(String s) {
String[] words = s.split(" ");
int maxlen = 0;
for (String w : words) maxlen = Math.max(maxlen, w.length());
List<String> res =new ArrayList<>();
for (int i = 0; i < maxlen; ++i) {
StringBuilder col =new StringBuilder();
for (String w : words) col.append(i < w.length() ? w.charAt(i) : ' ');
int end = col.length();
while (end > 0 && col.charAt(end-1) ==' ') end--;
res.add(col.substring(0, end));
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funprintVertically(s: String): List<String> {
val words = s.split(" ")
val maxlen = words.maxOf { it.length }
val res = mutableListOf<String>()
for (i in0 until maxlen) {
var col = ""for (w in words) col +=if (i < w.length) w[i] else' ' res.add(col.rstrip())
}
return res
}
}
privatefunString.rstrip() = this.replace(Regex(" +$"), "")
1
2
3
4
5
6
7
8
9
10
from typing import List
classSolution:
defprintVertically(self, s: str) -> List[str]:
words = s.split()
maxlen = max(len(w) for w in words)
res = []
for i in range(maxlen):
col =''.join(w[i] if i < len(w) else' 'for w in words).rstrip()
res.append(col)
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnprint_vertically(s: String) -> Vec<String> {
let words: Vec<&str>= s.split_whitespace().collect();
let maxlen = words.iter().map(|w| w.len()).max().unwrap();
letmut res = Vec::new();
for i in0..maxlen {
letmut col = String::new();
for w in&words {
if i < w.len() { col.push(w.chars().nth(i).unwrap()); } else { col.push(' '); }
}
while col.ends_with(' ') { col.pop(); }
res.push(col);
}
res
}
}