Copy public class Solution {
public List < String > fullJustify ( String [] words , int maxWidth) {
List < String > rst = new ArrayList <>();
if (words == null || words . length == 0 ) {
return rst;
}
// count 是上一次计算的单词的长度,last 是记录下一个单词的开始
int count = 0 , last = 0 ;
for ( int i = 0 ; i < words . length ; i ++ ) {
// words[i].length() 是尝试放当前的单词
// (i - last) 是这一行单词之间的间隔个数
// 它们的和用来判断这个单词放在这里是否会超过 L
if (count + words[i] . length () + (i - last) > maxWidth) {
int numOfSpace = 0 ;
int extraSpace = 0 ;
// 因为 words[i] 尝试失败了,所以间隔数减去 1
if (i - last - 1 > 0 ) { // 计算要放几个 space 以及是否需要 extra space
numOfSpace = (maxWidth - count) / (i - last - 1 );
extraSpace = (maxWidth - count) % (i - last - 1 );
}
StringBuilder sb = new StringBuilder() ;
for ( int j = last; j < i; j ++ ) {
sb . append (words[j]);
if (j < i - 1 ) { // words[i - 1] 之后就不用填空格了,所以这里是 j < i - 1
for ( int k = 0 ; k < numOfSpace; k ++ ) {
sb . append ( " " );
}
if (extraSpace > 0 ) {
sb . append ( " " );
}
extraSpace -- ;
}
}
// 这个 for loop 用来处理只有一个单词还没有填满一行的情况
for ( int j = sb . length (); j < maxWidth; j ++ ) {
sb . append ( " " );
}
rst . add ( sb . toString ());
count = 0 ;
last = i; // 下一个单词的开始
}
count += words[i] . length ();
}
// 单独处理最后一行
StringBuilder sb = new StringBuilder() ;
for ( int i = last; i < words . length ; i ++ ) {
sb . append (words[i]);
if ( sb . length () < maxWidth) {
sb . append ( " " );
}
}
for ( int i = sb . length (); i < maxWidth; i ++ ) {
sb . append ( " " );
}
rst . add ( sb . toString ());
return rst;
}
}