Skip to content

Commit e97a692

Browse files
68. Text Justification (java)
1 parent 0124e00 commit e97a692

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public List<String> fullJustify(String[] words, int maxWidth) {
3+
ArrayList<String> res = new ArrayList<>();
4+
if (words == null || words.length == 0) return res;
5+
int count = 0, last = 0;
6+
for (int i = 0; i < words.length; i++) {
7+
if (count + words[i].length() + (i - last) > maxWidth) {
8+
int spaceNum = 0, extraNum = 0;
9+
if (i - last - 1 > 0) {
10+
spaceNum = (maxWidth - count) / (i - last - 1);
11+
extraNum = (maxWidth - count) % (i - last - 1);
12+
}
13+
StringBuilder str = new StringBuilder();
14+
for (int j = last; j < i; j++) {
15+
str.append(words[j]);
16+
if (j < i - 1) {
17+
for (int k = 0; k < spaceNum; k++) str.append(" ");
18+
if (extraNum > 0) str.append(" ");
19+
extraNum--;
20+
}
21+
}
22+
for (int j = str.length(); j < maxWidth; j++) str.append(" ");
23+
res.add(str.toString());
24+
count = 0;
25+
last = i;
26+
}
27+
count += words[i].length();
28+
}
29+
StringBuilder str = new StringBuilder();
30+
for (int i = last; i < words.length; i++) {
31+
str.append(words[i]);
32+
if (str.length() < maxWidth) str.append(" ");
33+
}
34+
for (int i = str.length(); i < maxWidth; i++) str.append(" ");
35+
res.add(str.toString());
36+
return res;
37+
}
38+
}

0 commit comments

Comments
 (0)