class Solution {
public:
vector<string> fullJustify(vector<string>& words, int m) {
vector<string> res;
int n = words.size();
vector<int> cnt(n);
for (int i = 0; i < n; i ++ )
cnt[i] += words[i].size();
int s = 0, num = 0, l = 0, N = 0; // r 行数 s 每行单词格子
for (int i = 0; i < n; i ++ ) {
s = 0, num = 0, l = i, N = 0;
while (i < n && N + cnt[i] + (i != l) <= m)
s += cnt[i], num ++ , N += cnt[i] + (i != l), i ++ ;
i -- ;
// 格子数量
int k = 0, mod = 0;
if (num != 1) {
k = (m - s) / (num - 1);
mod = (m - s) % (num - 1);
}
// int k = 0, mod = 0;
string ans;
if (i != n - 1) {
for (int j = l; j < i; j ++ )
{
ans += words[j];
int a = k;
while (a -- ) ans += ' ';
if (mod -- > 0) ans += ' ';
}
ans += words[i];
}
else if (i == n - 1) {
for (int j = l; j <= i; j ++ ) {
ans += words[j];
if (num - 1 > 0) ans += ' ', num -- ;
}
}
while (ans.size() < m) ans += ' ';
res.push_back(ans);
}
return res;
}
};