没啥难的,就是麻烦点。
cpp
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> ret;
vector<string> temp;
int w = 0;
int total = 0;
int spaces;
int a, b;
string line;
for (int i = 0; i < words.size(); i++) {
if (w + words[i].length() > maxWidth) {
spaces = maxWidth - total;
line = "";
if (temp.size() == 1) {
line = temp[0];
for (int j = 0; j < spaces; j++) {
line += " ";
}
} else {
a = spaces / (temp.size() - 1);
b = spaces % (temp.size() - 1);
for (int j = 0; j < temp.size(); j++) {
line += temp[j];
if (j == temp.size() - 1) {
break;
}
for (int k = 0; k < a; k++) {
line += " ";
}
if (b > 0) {
line += " ";
--b;
}
}
}
ret.push_back(line);
temp.clear();
w = 0;
total = 0;
}
temp.push_back(words[i]);
w += words[i].length() + 1;
total += words[i].length();
}
line = "";
for (int i = 0; i < temp.size(); i++) {
if (i) {
line += " ";
}
line += temp[i];
}
while (line.size() < maxWidth) {
line += " ";
}
ret.push_back(line);
return ret;
}
};