-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path068. Text Justification.java
78 lines (64 loc) · 2.23 KB
/
068. 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// https://leetcode.com/problems/text-justification
public class Solution {
public int getLineWidth(List<String> words) {
int width = 0;
for (String word : words) {
width += word.length() + 1;
}
return width;
}
public String formatLine(List<String> words, int maxWidth, boolean lastSentence) {
StringBuilder sb = new StringBuilder();
if (words.size() == 1 || lastSentence) { // left-justified single-word line
for (String word : words) {
sb.append(word);
if (sb.length() < maxWidth) {
sb.append(" ");
}
}
while (sb.length() < maxWidth) {
sb.append(" ");
}
} else {
List<StringBuilder> wordBuilder = new ArrayList<>();
int wordLength = 0;
for (String word : words) {
wordBuilder.add(new StringBuilder(word));
wordLength += word.length();
}
int spaceToDist = maxWidth - wordLength;
int i = 0;
while (spaceToDist > 0) {
wordBuilder.get(i).append(" ");
spaceToDist--;
i++;
if (i == words.size() - 1) {
i = 0;
}
}
for (StringBuilder wBuilder : wordBuilder) {
sb.append(wBuilder);
}
}
return sb.toString();
}
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> lines = new ArrayList<>();
if (maxWidth == 0) {
lines.add("");
return lines;
}
List<String> cLine = new ArrayList<>();
for (String word : words) {
if (getLineWidth(cLine) + word.length() <= maxWidth) {
cLine.add(word);
} else {
lines.add(formatLine(cLine, maxWidth, false));
cLine = new ArrayList<>();
cLine.add(word);
}
}
lines.add(formatLine(cLine, maxWidth, true));
return lines;
}
}