没有复杂的算法,纯粹的模拟题
先试探,计算出一行能放几个单词
然后计算出单词之间有几个空格,注意,如果空格总长度无法整除空格数,前面的空格长度通通+1
最后放单词、放空格,组成一行,加入结果中
对于最后一行要特殊处理
代码:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> text;
int n = words.size(); int i = ;
int j = ; while ((i = j) < n) {
int wordsLen = ;
// 试探
while (j < n && wordsLen + words[j].length() + j - i <= L) {
wordsLen += words[j].length();
j++;
}
// 特殊处理最后一行
if (j == n) {
string line = words[i];
for (int k = i + ; k < j; k++)
line += " " + words[k];
line += string(L - wordsLen - (j - i - ), ' ');
text.push_back(line);
break;
} if (j == i + ) // 只有一个单词的行也单独处理,避免除0
text.push_back(words[j - ] + string(L - words[j - ].length(), ' '));
else { // 普通情况
int padLen = (L - wordsLen) / (j - i - );
int remainNum = L - wordsLen - padLen * (j - i - );
string line = words[i];
for (int k = i + ; k < j; k++) {
string pad(padLen, ' ');
if (remainNum > ) {
pad += " ";
remainNum--;
}
line += pad + words[k];
}
text.push_back(line);
}
} return text;
}