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. "
]
思路:一行一行的放,每次放之前判断能不能放进去,同时放的时候maintain一个当前的len值,每次len + 1(空格) + wordlength <= maxLength就可以放下,否则另起一行,最后even一下每一行即可。最后一行要求靠左,另外不可整除的空格,尽量放左边。我的代码比较ugly,但是也AC了, 要是谁有更简洁的代码,可以留言,互相交流~
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
//special case
List<String> res = new ArrayList<>();
if (words.length == 0) return res;
//general case
List<String> list = new ArrayList<>();
list.add(words[0]);
int len = words[0].length();
for (int i = 1; i < words.length; i++) {
if (len + 1 + words[i].length() <= maxWidth) {
len = len + 1 + words[i].length();
list.add(words[i]);
} else {
even(res, list, maxWidth, len);
list = new ArrayList<String>();
list.add(words[i]);
len = words[i].length();
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
if (i != list.size() - 1) {
sb.append(" ");
}
}
for (int i = 0; i < maxWidth - len; i++) {
sb.append(" ");
}
res.add(sb.toString());
return res;
}
public void even(List<String> res, List<String> list, int maxWidth, int len) {
int num = list.size(), blankNum = maxWidth - len;
int[] count = new int[num - 1];
StringBuilder sb = new StringBuilder();
if (num - 1 == 0) {
sb.append(list.get(0));
for (int i = 0; i < blankNum; i++) {
sb.append(" ");
}
res.add(sb.toString());
return;
}
int base = blankNum / (num - 1), rest = blankNum % (num - 1);
for (int i = 0; i < num - 1; i++) {
count[i] = base;
if (rest > 0) {
count[i]++;
rest--;
}
}
for (int i = 0; i < num; i++) {
sb.append(list.get(i));
if (i == num - 1) continue;
for (int j = 0; j < count[i] + 1; j++) {
sb.append(" ");
}
}
res.add(sb.toString());
}
}