-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTextJustification.java
57 lines (50 loc) · 1.87 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
55
56
57
import java.util.ArrayList;
import java.util.List;
/**
* Created by cpacm on 2017/7/6.
*/
public class TextJustification {
public static void main(String[] args) {
System.out.println(fullJustify(new String[]{"This", "is", "an", "example", "of", "text", "justification."}, 15));
}
public static List<String> fullJustify(String[] words, int L) {
List<String> lines = new ArrayList<String>();
int index = 0;
while (index < words.length) {
int count = words[index].length();
int last = index + 1;
while (last < words.length) {
if (words[last].length() + count + 1 > L) break;
count += words[last].length() + 1;
last++;
}
StringBuilder builder = new StringBuilder();
int diff = last - index - 1;
// if last line or number of words in the line is 1, left-justified
if (last == words.length || diff == 0) {
for (int i = index; i < last; i++) {
builder.append(words[i] + " ");
}
builder.deleteCharAt(builder.length() - 1);
for (int i = builder.length(); i < L; i++) {
builder.append(" ");
}
} else {
// middle justified
int spaces = (L - count) / diff;
int r = (L - count) % diff;
for (int i = index; i < last; i++) {
builder.append(words[i]);
if (i < last - 1) {
for (int j = 0; j <= (spaces + ((i - index) < r ? 1 : 0)); j++) {
builder.append(" ");
}
}
}
}
lines.add(builder.toString());
index = last;
}
return lines;
}
}