思路:
这题用的强行模拟, 自己做出来了还挺高兴的, 会遍历两次words, 所以是O(n)的时间复杂度, 用时0ms.
int generateNextString(vector<string>& words, string& candidate, int start, int maxWidth) {
// 如果当前是最后一个单词, 直接向左对齐,然后补空格,返回
if (start == words.size() - 1) {
candidate = words.back();
candidate += string(maxWidth - candidate.length(), ' ');
return words.size() - 1;
}
// 计算当前串能容纳到words中的哪个字符串
int end = -1, count = 0;
for (int i = start; i < words.size(); i++) {
if (count + words[i].length() + 1 > maxWidth + 1) {
end = i - 1;
break;
}
else count += words[i].length() + 1;
}
// 如果end没有变化, 就说明从start到words最后都能放到当前串
if (end == -1) {
end = words.size() - 1;
for (int i = start; i <= end; i++) {
candidate += words[i];
candidate += ' ';
}
candidate += string(maxWidth - candidate.length(), ' ');
return end;
}
// 如果只能放下一个串
if (end == start) {
candidate = words[start];
candidate += string(maxWidth - candidate.length(), ' ');
return end;
}
// 最后的情况, end在start和words最后一个元素的索引之间
count -= end - start + 1;
int baseIntervalSpaces = (maxWidth - count) / (end - start);
int extraIntervalSpaces = (maxWidth - count) % (end - start);
for (int i = start; i <= end; i++) {
candidate += words[i];
if (i == end) break;
candidate += string(baseIntervalSpaces, ' ');
if (extraIntervalSpaces-- > 0)
candidate += ' ';
}
return end;
}
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> res;
string candidate = "";
int i = 0;
while (i < words.size()) {
i = generateNextString(words, candidate, i, maxWidth) + 1;
res.push_back(candidate);
candidate.clear();
}
return res;
}