-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathText Justification.java
More file actions
48 lines (48 loc) · 1.74 KB
/
Text Justification.java
File metadata and controls
48 lines (48 loc) · 1.74 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
45
46
47
48
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> result = new ArrayList<>();
int idx = 0;
List<String> line = new ArrayList<>();
int currLineLength = 0;
StringBuilder sb = new StringBuilder();
while (idx < words.length) {
if (line.size() + currLineLength + words[idx].length() > maxWidth) {
int spaces = maxWidth - currLineLength;
if (line.size() == 1) {
result.add(line.get(0) + " ".repeat(spaces));
line.clear();
currLineLength = 0;
continue;
}
int spacesPerWord = spaces / (line.size() - 1);
int extraSpaces = spaces % (line.size() - 1);
for (int i = 0; i < line.size() - 1; i++) {
sb.append(line.get(i));
sb.append(" ".repeat(spacesPerWord));
if (extraSpaces-- > 0) {
sb.append(" ");
}
}
sb.append(line.getLast());
result.add(sb.toString());
sb.setLength(0);
line.clear();
currLineLength = 0;
continue;
}
line.add(words[idx]);
currLineLength += words[idx].length();
idx++;
}
for (int i = 0; i < line.size(); i++) {
sb.append(line.get(i));
if (i != line.size() - 1) {
sb.append(" ");
}
}
int trailSpaceLength = maxWidth - sb.length();
sb.append(" ".repeat(trailSpaceLength));
result.add(sb.toString());
return result;
}
}