2
public List<String> fullJustify(String[] words, int maxWidth) {3
List<String> unBalanced = new ArrayList<>();4
List<String> balanced = new ArrayList<>();7
StringBuffer sb = new StringBuffer();8
// Following code creates a list of unbalanced lines by appending words and 1 space between them9
for (String word : words) {11
if (sb.length() == 0) {14
if (sb.length() + 1 + word.length() <= maxWidth) {15
sb.append(" " + word);17
unBalanced.add(sb.toString());18
sb = new StringBuffer(word);23
if (sb.length() > 0) {24
unBalanced.add(sb.toString());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 in32
// any sentence and hence no spaces33
if (j == unBalanced.size() - 1 || !line.contains(" ")) {34
int tempSpaces = maxWidth - lineB.length();35
while (tempSpaces > 0) {39
balanced.add(lineB.toString());43
// The following block checks for each character and appends 1 space during each loop44
// If there are still spaces left at the end of the String, again start from beggining and45
// append spaces after each word46
while (numSpaces > 0) {48
while (i < lineB.length() - 1) {49
if (lineB.charAt(i) == ' ' && lineB.charAt(i + 1) != ' ') {50
lineB.insert(i + 1, ' ');53
if (numSpaces == 0) break;58
balanced.add(lineB.toString());