-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1324-PrintWordVertically.java
More file actions
44 lines (38 loc) · 1.14 KB
/
Copy path1324-PrintWordVertically.java
File metadata and controls
44 lines (38 loc) · 1.14 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public List<String> printVertically(String s) {
List<String> res = new ArrayList<>();
String[] arr = s.split(" ");
int maxLength = getMaxLength(arr);
char[][] board = new char[maxLength][arr.length];
for (int i = 0; i < board.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < board[0].length; j++) {
String curr = arr[j];
if (i < curr.length())
sb.append(curr.charAt(i));
else {
sb.append(' ');
}
}
res.add(trimTrailing(sb.toString()));
}
return res;
}
private String trimTrailing(String str) {
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) != ' ') {
return str.substring(0, i + 1);
}
}
return "";
}
private int getMaxLength(String[] arr) {
int max = 0;
for (String s : arr) {
if (s.length() > max) {
max = s.length();
}
}
return max;
}
}