1
+ // Runtime: 4 ms (Top 15.97%) | Memory: 42.1 MB (Top 76.75%)
1
2
class Solution {
2
3
public List <String > fullJustify (String [] words , int maxWidth ) {
3
4
List <String > unBalanced = new ArrayList <>();
4
5
List <String > balanced = new ArrayList <>();
5
6
int numSpaces = 0 ;
6
-
7
+
7
8
StringBuffer sb = new StringBuffer ();
8
- //Following code creates a list of unbalanced lines by appending words and 1 space between them
9
+ //Following code creates a list of unbalanced lines by appending words and 1 space between them
9
10
for (String word : words ){
10
-
11
+
11
12
if (sb .length () == 0 ){
12
13
sb .append (word );
13
14
}else {
@@ -18,18 +19,18 @@ public List<String> fullJustify(String[] words, int maxWidth) {
18
19
sb = new StringBuffer (word );
19
20
}
20
21
}
21
-
22
+
22
23
}
23
-
24
+
24
25
if (sb .length () >0 ){
25
26
unBalanced .add (sb .toString ());
26
27
}
27
-
28
+
28
29
for (int j = 0 ; j < unBalanced .size (); j ++){
29
30
String line = unBalanced .get (j );
30
31
numSpaces = maxWidth - line .length ();
31
32
StringBuffer lineB = new StringBuffer (line );
32
- //This if block handles either last line or the scenario where in there's only one word in any sentence and hence no spaces
33
+ //This if block handles either last line or the scenario where in there's only one word in any sentence and hence no spaces
33
34
if (j == unBalanced .size ()-1 || !line .contains (" " )){
34
35
int tempSpaces = maxWidth - lineB .length ();
35
36
while (tempSpaces > 0 ){
@@ -40,7 +41,7 @@ public List<String> fullJustify(String[] words, int maxWidth) {
40
41
continue ;
41
42
};
42
43
// The following block checks for each character and appends 1 space during each loop
43
- //If there are still spaces left at the end of the String, again start from beggining and append spaces after each word
44
+ //If there are still spaces left at the end of the String, again start from beggining and append spaces after each word
44
45
while (numSpaces > 0 ){
45
46
int i = 0 ;
46
47
while (i < lineB .length () - 1 ){
@@ -55,7 +56,7 @@ public List<String> fullJustify(String[] words, int maxWidth) {
55
56
}
56
57
balanced .add (lineB .toString ());
57
58
}
58
-
59
+
59
60
return balanced ;
60
61
}
61
- }
62
+ }
0 commit comments