class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<vector<string> > answer;
vector<string> now;
int nowwidth=0;
for(int i=0;i<words.size();i++){
nowwidth += words[i].length();
if(nowwidth>maxWidth){
answer.push_back(now);
now.clear();
nowwidth = words[i].length()+1;
now.push_back(words[i]);
}
else if(nowwidth==maxWidth){
now.push_back(words[i]);
answer.push_back(now);
now.clear();
nowwidth = 0;
}
else{
now.push_back(words[i]);
nowwidth += 1;
}
}
if(!now.empty()){
answer.push_back(now);
now.clear();
}
for(int i=0;i<answer.size();i++){
string all;
if(answer[i].size()==1||i==answer.size()-1){
for(int j=0;j<answer[i].size();j++){
all =all+answer[i][j];
if(all.length()<maxWidth) all = all+' ';
}
while(all.length()<maxWidth) all = all + ' ';
}
else{
for(int j=1;j<=answer[i].size()-1;j+=2){
answer[i].insert(answer[i].begin()+j," ");
}
int all_num=0;
for(int j=0;j<answer[i].size();j++) all_num += answer[i][j].length();
bool flag = true;
while(all_num<maxWidth&&flag){
for(int j=1;j<answer[i].size();j+=2){
if(all_num<maxWidth) {
answer[i][j] = answer[i][j]+' ';
all_num++;
}
else {
flag = false;
break;
}
}
}
for(int j=0;j<answer[i].size();j++) all = all + answer[i][j];
}
now.push_back(all);
}
return now;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/83be0e0b6ecbb06a7bf1014bbe85a125.png)