# Easy to understand Java solution

• public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
ArrayList<String> result = new ArrayList<String>();
if(words.length == 0) return result;

int start = 0, wordsLengthInCurLine = 0, wordsInCurLine = 0;

for(int i = 0; i < words.length; i++) {
wordsInCurLine++;

// length for i-1 words + currentWordLen + numOfMinSpacesBetweenWords
int lineLength = wordsLengthInCurLine + words[i].length() + (i-start);

if(lineLength == maxWidth) {
start = i+1;
wordsLengthInCurLine = 0;
wordsInCurLine = 0;
}
else if(lineLength > maxWidth) {
start = i;
wordsLengthInCurLine = words[i].length();
wordsInCurLine = 1;
}
else {
wordsLengthInCurLine += words[i].length();
}
}

if(wordsInCurLine > 0) {
StringBuffer sb = new StringBuffer(createLine(words, start, words.length-1, words.length-1-start));
for(int s = 0; s < maxWidth-wordsLengthInCurLine-(words.length-1-start); s++) {
sb.append(' ');
}
}

return result;
}

String createLine(String[] words, int start, int end, int numSpaces) {
StringBuffer line = new StringBuffer();
int numOfWords = end - start + 1;

for(int i = start; i < end; i++) {
line.append(words[i]);
numOfWords--;
int spaceBetweenWords = (int)Math.ceil((double)numSpaces/numOfWords);
for(int s = 0; s < spaceBetweenWords; s++) {
line.append(' ');
}

numSpaces -= spaceBetweenWords;
}

line.append(words[end]);
for(int s = 0; s < numSpaces; s++) {
line.append(' ');
}

return line.toString();
}
}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.