-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path68.Text-Justification.java
65 lines (59 loc) · 2.07 KB
/
68.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
// https://leetcode.com/problems/text-justification/
//
// algorithms
// Hard (23.16%)
// Total Accepted: 95,628
// Total Submissions: 412,929
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
ArrayList<String> l = new ArrayList<>();
LinkedList<String> tmp = new LinkedList<>();
int wordSum = 0, numSum = 0;
for (String w : words) {
int wLen = w.length();
if (wordSum + numSum + wLen <= maxWidth) {
wordSum += wLen;
numSum++;
tmp.offer(w);
} else {
StringBuilder sb = new StringBuilder();
if (numSum == 1) {
sb.append(tmp.peek());
for (int i = 0; i < maxWidth - wordSum; i++) {
sb.append(" ");
}
} else {
int[] space = new int[numSum - 1];
int spaceSum = maxWidth - wordSum;
Arrays.fill(space, spaceSum / (numSum - 1));
for (int i = 0; i < spaceSum % (numSum - 1); i++) {
space[i]++;
}
for (int i = 0; i < numSum - 1; i++) {
sb.append(tmp.pollFirst());
for (int j = 0; j < space[i]; j++) {
sb.append(" ");
}
}
sb.append(tmp.peek());
}
l.add(sb.toString());
wordSum = wLen;
numSum = 1;
tmp.clear();
tmp.offer(w);
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numSum - 1; i++) {
sb.append(tmp.pollFirst());
sb.append(" ");
}
sb.append(tmp.peek());
for (int i = 0; i < maxWidth - wordSum - (numSum - 1); i++) {
sb.append(" ");
}
l.add(sb.toString());
return l;
}
}