public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<List<String>> res = new ArrayList<>();
List<String> temp1 = new ArrayList<>();
int len = 0;
for (String word : words) {
len = len + word.length() + 1;
if (len - 1 > maxWidth) {
res.add(temp1);
len = word.length() + 1;
temp1 = new ArrayList<>();
}
temp1.add(word);
}
res.add(temp1);//先把每一行的单词取出来
List<String> result = new ArrayList<>();
for (int j=0;j<res.size()-1;j++) {
List<String> templist = res.get(j);
String temp = "";
int l = templist.size();
if (l == 1) {
String tempstr = templist.get(0);
temp += tempstr;
while (temp.length() != maxWidth) {
temp += " ";
}
} else {
int sum = 0;
for (String word : templist) {
sum += word.length();
}
int spaces = maxWidth - sum;//空格的总数量
int space = spaces / (l - 1);//加入空格的数量
int remain = spaces - space * (l - 1);//见下面具体解释
String blank = "";
for (int i = 0; i < space; i++) {
blank += " ";//加入的空格字符串
}
for (int i = 0; i < remain; i++) {//见下面具体解释
temp += templist.get(i);
temp += blank;
temp += " ";
}
for (int i = remain; i < l - 1; i++) {
temp += templist.get(i);
temp += blank;
}
temp += templist.get(l - 1);
}
result.add(temp);
}
//最后一行左对齐,单独处理
List<String> templist = res.get(res.size()-1);
String temp = "";
for(String word:templist){
temp += word;
temp +=" ";
}if(temp.length()>maxWidth){//如果多加了一个空格,就把这个多加的空格删掉
temp = temp.substring(0,temp.length()-1);
}while(temp.length()<maxWidth){
temp +=" ";
}
result.add(temp);
return result;
}
具体解释: