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
For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as
[
"This is an",
"example of text",
"justification. "
]
public ArrayList<String> fullJustify(String[] words, int L) {
ArrayList<String> result = new ArrayList<String>();
if (words == null || words.length == 0)
return result;
int begin = 0, end = 0; // words[begin...end-1] as a line
while (begin < words.length) {
// Determine end such that words[begin...end-1] fit in a line and
// words[begin...end] do not.
int currentLength = words[begin].length();
for (end = begin+1; end < words.length; end++) {
if (currentLength + words[end].length() + 1 <= L)
currentLength += words[end].length() + 1;
else
break;
}
// Construct a justified line with words[begin...end-1]
StringBuilder temp = new StringBuilder();
temp.append(words[begin]);
if (end == words.length || end == begin+1) { // Last line or a line with only one word
// Left justified
for (int i = begin+1; i < end; i++) {
temp.append(' ');
temp.append(words[i]);
}
for (int i = 0; i < L - currentLength; i++)
temp.append(' ');
} else { // Regular lines
// Fully justified
int spaceInBetween = end - begin - 1;
double spaces = L - currentLength + spaceInBetween;
for (int i = begin+1; i < end; i++) {
for (int j = 0; j < spaces/spaceInBetween; j++) {
temp.append(' ');
}
spaces -= Math.ceil(spaces/spaceInBetween);
spaceInBetween--;
temp.append(words[i]);
}
}
// Add the line to the resulting list, and slide the window to the next position
result.add(temp.toString());
begin = end;
}
return result;
}
Read full article from LeetCode - Text Justification | Darren's Blog
No comments:
Post a Comment