### 问题描述

https://leetcode.com/problems/text-justification/#/description

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.

### 算法

words=["This", "is", "an", "example", "of", "text", "justification."]，L=16

1. 每一行的单词要尽可能的多，并且要左右都能顶格，不足L个字符时，可以使用空格' '代替字母
2. 每一行单词之间的空格要尽可能地均匀，不能满足均匀的前提下，左边的要比右边的多
3. 最后一行只要满足左边顶格，并且单词之间不要有多余空格

### 代码

        public List<String> fullJustify(String[] words, int maxWidth) {
List<String> lines = new ArrayList<>();
int cur = 0;
while(cur < words.length) {
int last = cur+1;
int cnt = words[cur].length(); // 单词的字母数
while(last < words.length) {
if(words[last].length() + cnt + 1 > maxWidth) {
break;
}
cnt += words[last].length()+1;
last++;
}
int gap = last - cur - 1;
StringBuilder sb = new StringBuilder();
if(last == words.length || gap == 0) { // 到了最后一行或者只有一个单词
for(int i=cur;i<last;i++) {
sb.append(words[i]+" ");
}
sb.deleteCharAt(sb.length()-1);
for(int i=sb.length();i<maxWidth;i++) {
sb.append(" ");
}
} else {
int spaces = (maxWidth - cnt) / gap;
int rem = (maxWidth - cnt) % gap;
for(int i=cur;i<last;i++) {
sb.append(words[i]);
if(i<last-1) {
for(int j=0;j<=(spaces+(i-cur<rem?1:0));j++) {
sb.append(" ");
}
}
}
}