贪心+模拟,注意细节
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> ans;
int left;
left = 0;
int sumlength = words[0].length();
if(1 == words.size()){
int index = 0;
string s(maxWidth, ' ');
for(char c : words[0]) s[index++] = c;
ans.push_back(s);
}
for(int i = 1; i < words.size(); i++){
if(sumlength + words[i].length() + 1 > maxWidth){
string s(maxWidth, ' ');
int num1 = 0;
int num2 = 0;
if(i - 1 - left == 0){
num1 = maxWidth - sumlength - 1;
}else{
num1 = (maxWidth - sumlength) / (i - 1 - left);
num2 = (maxWidth - sumlength) % (i - 1 - left);
}
int index = 0;
for(int j = left; j < i; j++){
for(char c : words[j]){
s[index++] = c;
}
index = index + num1 + 1;
if(j - left < num2) index++;
}
ans.push_back(s);
left = i;
sumlength = words[i].length();
if(i + 1 >= words.size()){
int index = 0;
string s(maxWidth, ' ');
for(char c : words[i]) s[index++] = c;
ans.push_back(s);
}
}else{
sumlength = sumlength + 1 + words[i].length();
if(i + 1 >= words.size()){
int index = 0;
string s(maxWidth, ' ');
for(int j = left; j <= i; j++){
for(char c : words[j]) s[index++] = c;
index++;
}
ans.push_back(s);
}
}
}
return ans;
}
};