-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathText Justification.java
37 lines (34 loc) · 1.18 KB
/
Text Justification.java
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
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> ans = new ArrayList<>();
List<StringBuilder> row = new ArrayList<>();
int rowLetters = 0;
for (final String word : words) {
if (rowLetters + row.size() + word.length() > maxWidth) {
final int spaces = maxWidth - rowLetters;
if (row.size() == 1) {
for (int i = 0; i < spaces; ++i)
row.get(0).append(" ");
} else {
for (int i = 0; i < spaces; ++i)
row.get(i % (row.size() - 1)).append(" ");
}
final String joinedRow =
row.stream().map(StringBuilder::toString).collect(Collectors.joining(""));
ans.add(joinedRow);
row.clear();
rowLetters = 0;
}
row.add(new StringBuilder(word));
rowLetters += word.length();
}
final String lastRow =
row.stream().map(StringBuilder::toString).collect(Collectors.joining(" "));
StringBuilder sb = new StringBuilder(lastRow);
final int spacesToBeAdded = maxWidth - sb.length();
for (int i = 0; i < spacesToBeAdded; ++i)
sb.append(" ");
ans.add(sb.toString());
return ans;
}
}