1
class Solution {
2
public List<String> fullJustify(String[] words, int maxWidth) {
3
List<String> unBalanced = new ArrayList<>();
4
List<String> balanced = new ArrayList<>();
5
int numSpaces = 0;
6

7
StringBuffer sb = new StringBuffer();
8
// Following code creates a list of unbalanced lines by appending words and 1 space between them
9
for (String word : words) {
10

11
if (sb.length() == 0) {
12
sb.append(word);
13
} else {
14
if (sb.length() + 1 + word.length() <= maxWidth) {
15
sb.append(" " + word);
16
} else {
17
unBalanced.add(sb.toString());
18
sb = new StringBuffer(word);
19
}
20
}
21
}
22

23
if (sb.length() > 0) {
24
unBalanced.add(sb.toString());
25
}
26

27
for (int j = 0; j < unBalanced.size(); j++) {
28
String line = unBalanced.get(j);
29
numSpaces = maxWidth - line.length();
30
StringBuffer lineB = new StringBuffer(line);
31
// This if block handles either last line or the scenario where in there's only one word in
32
// any sentence and hence no spaces
33
if (j == unBalanced.size() - 1 || !line.contains(" ")) {
34
int tempSpaces = maxWidth - lineB.length();
35
while (tempSpaces > 0) {
36
lineB.append(" ");
37
tempSpaces--;
38
}
39
balanced.add(lineB.toString());
40
continue;
41
}
42
;
43
// The following block checks for each character and appends 1 space during each loop
44
// If there are still spaces left at the end of the String, again start from beggining and
45
// append spaces after each word
46
while (numSpaces > 0) {
47
int i = 0;
48
while (i < lineB.length() - 1) {
49
if (lineB.charAt(i) == ' ' && lineB.charAt(i + 1) != ' ') {
50
lineB.insert(i + 1, ' ');
51
i++;
52
numSpaces--;
53
if (numSpaces == 0) break;
54
}
55
i++;
56
}
57
}
58
balanced.add(lineB.toString());
59
}
60

61
return balanced;
62
}
63
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0