要求:最后一行或者一个单词的左对齐(空格在右边),其他的空格只能在单词之间且左边的间隔先分配空格
思路:参考https://leetcode.cn/problems/text-justification/solution/c-by-zhong-xia-w-1ty1/
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
//遍历字符串,使用贪心思想来放置单词
//我们应该确定一行要放几个单词,需要几个空格
//同时单词和单词之间需要有至少一个空格
int i = 0,n = words.size();
vector<string> result;
while(i < n){
//确定能放几个单词
int start = i,sum = words[start].size();
i++;
while(i < n && sum <= maxWidth){
sum += words[i].size() + 1;
i++;
}
//最后一行要左对齐
if(i == n && sum <= maxWidth){
string str = "";
for(int j = start;j < i - 1;j++){
str += words[j] + " ";
}
//此举是为了把剩余的位置用空格补上
str += words[i - 1];
str += string(maxWidth - str.size(),' ');
result.emplace_back(str);
}
//非最后一行的处理方式
else{
i--;
int num = i - start;
//这是多了的空格,需要尽可能的平均分配(这里我们每个单词之间已经默认出现一个空格了)
int diff = maxWidth - (sum - (words[i].size() + 1));
//只有一个直接加入就可以了
if(num == 1){
result.emplace_back(words[start] + string(diff,' '));
continue;
}
int a = diff / (num - 1);
int b = diff % (num - 1);
//根据分配好的空格构建字符串,不平均的要紧着左边来
string str = "";
for(int j = 0;j < num - 1;j++){
str += words[start + j] + (j < b ? string(a + 2,' ') : string(a + 1,' '));
}
str += words[start + num - 1];
result.emplace_back(str);
}
}
return result;
}
};