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. "
]
1、算出當前行能放的單詞數(shù)和所用長度;2、如果當前行將包括最后一個單詞或者只包含一個單詞,則右邊不全空格;3、否則,算出單詞間平均補全的空格數(shù),以及左側需要額外加1的空格位置。
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new ArrayList<>();
if (words == null || words.length == 0) {
return res;
}
for (int index = 0; index < words.length; ) {
StringBuilder buff = new StringBuilder();
int count = words[index].length();
int last = index + 1;
while (last < words.length && count + 1 + words[last].length() <= maxWidth) {
count += 1 + words[last].length();
last++;
}
int diff = last - index - 1;
if (last == words.length || diff == 0) {
for (int i = index; i < last; i++) {
buff.append(words[i] + ' ');
}
buff.deleteCharAt(buff.length() - 1);
for (int i = buff.length() + 1; i <= maxWidth; i++) {
buff.append(' ');
}
} else {
int spaces = (maxWidth - count) / diff;
int left = (maxWidth - count) % diff;
for (int i = index; i < last; i++) {
buff.append(words[i]);
if (i < last - 1) {
for (int j = 0; j <= spaces + (i - index < left ? 1 : 0); j++) {
buff.append(' ');
}
}
}
}
res.add(buff.toString());
index = last;
}
return res;
}