[LeetCode] Print Words Vertically

1324. Print Words Vertically

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.

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
class Solution {
vector<string> parse(string s) {
string token = "";
vector<string> res;
for(auto& ch : s) {
if(ch == ' ') {
res.push_back(token);
token = "";
} else token.push_back(ch);
}
res.push_back(token);
return res;
}
public:
vector<string> printVertically(string s) {
vector<string> vs = parse(s);
int n = 1;
for(auto& s : vs) n = max(n, (int)s.length());
vector<string> res(n);
for(int i = 0; i < vs.size(); i++) {
for(int j = 0; j < vs[i].length(); j++) {
while(res[j].length() < i) res[j].push_back(' ');
res[j].push_back(vs[i][j]);
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/06/PS/LeetCode/print-words-vertically/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.