class Solution {
public:
vector<string> fullJustify(vector<string>& words, int L) {
vector<string> ans;
const int n = words.size();
for (int i = 0; i < n;) {
int num = 0, len = 0;
while (i + num < n && words[i + num].size() + len <= L - num) {
len += words[i + num].size();
++num;
}
string tmp = words[i];
for (int j = 1; j < num; ++j) {
if (i + num >= n) tmp += " ";
else tmp += string((L - len) / (num - 1) + (j <= (L - len) % (num - 1)), ' ');
tmp += words[i + j];
}
tmp += string(L - tmp.size(), ' ');
ans.push_back(tmp);
i += num;
}
return ans;
}
};
public:
vector<string> fullJustify(vector<string>& words, int L) {
vector<string> ans;
const int n = words.size();
for (int i = 0; i < n;) {
int num = 0, len = 0;
while (i + num < n && words[i + num].size() + len <= L - num) {
len += words[i + num].size();
++num;
}
string tmp = words[i];
for (int j = 1; j < num; ++j) {
if (i + num >= n) tmp += " ";
else tmp += string((L - len) / (num - 1) + (j <= (L - len) % (num - 1)), ' ');
tmp += words[i + j];
}
tmp += string(L - tmp.size(), ' ');
ans.push_back(tmp);
i += num;
}
return ans;
}
};
评论
发表评论