-
Notifications
You must be signed in to change notification settings - Fork 69
/
TextJustification.java
54 lines (41 loc) Β· 1.9 KB
/
TextJustification.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
public List<String> fullJustify(String[] words, int maxWidth) {
int left = 0; List<String> result = new ArrayList<>();
while (left < words.length) {
int right = findRight(left, words, maxWidth);
result.add(justify(left, right, words, maxWidth));
left = right + 1;
}
return result;
}
private int findRight(int left, String[] words, int maxWidth) {
int right = left;
int sum = words[right++].length();
while (right < words.length && (sum + 1 + words[right].length()) <= maxWidth)
sum += 1 + words[right++].length();
return right - 1;
}
private String justify(int left, int right, String[] words, int maxWidth) {
if (right - left == 0) return padResult(words[left], maxWidth);
boolean isLastLine = right == words.length - 1;
int numSpaces = right - left;
int totalSpace = maxWidth - wordsLength(left, right, words);
String space = isLastLine ? " " : blank(totalSpace / numSpaces);
int remainder = isLastLine ? 0 : totalSpace % numSpaces;
StringBuilder result = new StringBuilder();
for (int i = left; i <= right; i++)
result.append(words[i])
.append(space)
.append(remainder-- > 0 ? " " : "");
return padResult(result.toString().trim(), maxWidth);
}
private int wordsLength(int left, int right, String[] words) {
int wordsLength = 0;
for (int i = left; i <= right; i++) wordsLength += words[i].length();
return wordsLength;
}
private String padResult(String result, int maxWidth) {
return result + blank(maxWidth - result.length());
}
private String blank(int length) {
return new String(new char[length]).replace('\0', ' ');
}