Skip to content

Commit 0beb82d

Browse files
authored
Create print-words-vertically.cpp
1 parent 8360f53 commit 0beb82d

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

C++/print-words-vertically.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<string> printVertically(string s) {
7+
vector<string> result, words;
8+
stringstream ss(s);
9+
string word;
10+
int max_len = 0;
11+
while (ss >> word) {
12+
words.emplace_back(word);
13+
max_len = max(max_len, int(word.size()));
14+
}
15+
for (int i = 0; i < max_len; ++i) {
16+
result.emplace_back();
17+
for (const auto& word : words) {
18+
result.back() += i < word.length() ? word[i] : ' ';
19+
}
20+
while (result.back().back() == ' ') {
21+
result.back().pop_back();
22+
}
23+
}
24+
return result;
25+
}
26+
};

0 commit comments

Comments
 (0)