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.
Example 1:
Input: s = "HOW ARE YOU" Output: ["HAY","ORO","WEU"] Explanation: Each word is printed vertically. "HAY" "ORO" "WEU"
Example 2:
Input: s = "TO BE OR NOT TO BE" Output: ["TBONTB","OEROOE"," T"] Explanation: Trailing spaces is not allowed. "TBONTB" "OEROOE" " T"
Example 3:
Input: s = "CONTEST IS COMING" Output: ["CIC","OSO","N M","T I","E N","S G","T"]
Constraints:
<li><code>1 <= s.length <= 200</code></li>
<li><code>s</code> contains only upper case English letters.</li>
<li>It's guaranteed that there is only one space between 2 words.</li>
class Solution:
def printVertically(self, s: str) -> List[str]:
words = s.split()
m, n = len(words), max(len(word) for word in words)
ans = []
for j in range(n):
t = []
for i in range(m):
word = words[i]
t.append(word[j] if j < len(word) else ' ')
ans.append(''.join(t).rstrip())
return ans
class Solution {
public List<String> printVertically(String s) {
String[] words = s.split(" ");
int m = words.length, n = maxLen(words);
List<String> ans = new ArrayList<>();
for (int j = 0; j < n; ++j) {
StringBuilder t = new StringBuilder();
for (int i = 0; i < m; ++i) {
String word = words[i];
t.append(j < word.length() ? word.charAt(j) : ' ');
}
ans.add(rstrip(t));
}
return ans;
}
private int maxLen(String[] words) {
int ans = 0;
for (String word : words) {
ans = Math.max(ans, word.length());
}
return ans;
}
private String rstrip(StringBuilder s) {
for (int i = s.length() - 1; i >= 0; --i) {
if (s.charAt(i) != ' ') {
return s.substring(0, i + 1);
}
}
return "";
}
}
class Solution {
public:
vector<string> printVertically(string s) {
stringstream in(s);
vector<string> words;
string word;
int n = 0;
while (in >> word) {
words.push_back(word);
n = max(n, (int)word.size());
}
int m = words.size();
vector<string> ans;
for (int j = 0; j < n; ++j) {
string t = "";
for (int i = 0; i < m; ++i) {
word = words[i];
t += j < word.size() ? word[j] : ' ';
}
while (t.back() == ' ') {
t.pop_back();
}
ans.push_back(t);
}
return ans;
}
};
func printVertically(s string) []string {
words := strings.Split(s, " ")
m := len(words)
var n int
for _, word := range words {
if n < len(word) {
n = len(word)
}
}
var ans []string
for j := 0; j < n; j++ {
var t []byte
for i := 0; i < m; i++ {
word := words[i]
if j < len(word) {
t = append(t, word[j])
} else {
t = append(t, ' ')
}
}
s = string(t)
ans = append(ans, rstrip(s))
}
return ans
}
func rstrip(s string) string {
for i := len(s) - 1; i >= 0; i-- {
if s[i] != ' ' {
return s[:i+1]
}
}
return s
}