Text Justification
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example, words: ["This", "is", "an", "example", "of", "text", "justification."] L: 16.
Return the formatted lines as: [ "This is an", "example of text", "justification. " ] Note: Each word is guaranteed not to exceed L in length.
public List<String> fullJustify(String[] words, int maxWidth) {
int currLineStart = 0, numWordsCurrLine = 0, currLineLength = 0;
List<String> result = new ArrayList();
// currLineStart is used for determining the first word of the current line
for (int i = 0; i < words.length; i++) {
numWordsCurrLine++;
// numWordsCurrLine - 1 is the smallest number of white spaces
int lookaheadLength = currLineLength + words[i].length() + (numWordsCurrLine - 1);
if (lookaheadLength == maxWidth) {
result.add(joinALineWithSpace(words, currLineStart, i, numWordsCurrLine - 1));
currLineStart = i + 1;
numWordsCurrLine = 0;
currLineLength = 0;
} else if (lookaheadLength > maxWidth) {
result.add(joinALineWithSpace(words, currLineStart, i - 1, maxWidth - currLineLength));
currLineStart = i;
numWordsCurrLine = 1;
currLineLength = words[i].length();
} else { //lookaheadLength > maxWidth
currLineLength += words[i].length();
}
}
// handle the last line, last line is left-aligned
if (numWordsCurrLine > 0) {
StringBuilder line = new StringBuilder(joinALineWithSpace(
words, currLineStart, words.length - 1, numWordsCurrLine - 1
));
for (int i = 0 ; i < maxWidth - currLineLength - (numWordsCurrLine - 1); i++) {
line.append(" ");
}
result.add(line.toString());
}
return result;
}
// Join words[start:end] with numSpaces space spread evenly
private String joinALineWithSpace(String[] words, int start, int end, int numSpaces) {
int numWordsCurrentLine = end - start + 1;
StringBuilder line = new StringBuilder();
for (int i = start; i < end; i++) {
line.append(words[i]);
numWordsCurrentLine--;
int numCurrSpace = (int)Math.ceil((double)numSpaces / numWordsCurrentLine);
for (int j = 0; j < numCurrSpace; j++) {
line.append(" ");
}
numSpaces -= numCurrSpace;
}
line.append(words[end]);
for (int i = 0; i < numSpaces; i++) {
line.append(" ");
}
return line.toString();
}