68. 文本左右对齐
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
//最后一行左对齐,或者这一行只包含一个单词左对齐
//包含多个单词 左右对齐
//先统计能放多少个单词
vector<string> res;
for(int i = 0; i < words.size(); ++i){
int j = i + 1;
int len = words[i].size();
while(j < words.size() && len + 1 + words[j].size() <= maxWidth) len += 1 + words[j++].size();
string line = "";
if(j == words.size() || j == i + 1) { //左对齐
line += words[i];
for(int k = i + 1; k < j; ++k) line += " " + words[k];
while(line.size() < maxWidth) line += " ";
}else{ //左右对齐
//cnt个空隙, r个空格要插
int cnt = j - i - 1, r = maxWidth - len + cnt;
line += words[i];
int k = 0;
//放左边多的
while(k < r % cnt) line += string(r / cnt + 1, ' ') + words[i + k + 1], ++k;
while(k < cnt) line += string(r / cnt, ' ') + words[i + k + 1], ++k;
//再放右边
}
res.push_back(line);
i = j - 1;
}
return res;
}
};