题里有的东西没说,debug各种各样的错误。像啊,很像,像什么呢,哈哈哈哈哈,懂的都懂,你懂了吗
#include<iostream>
#include<vector>
class Solution {
public:
std::vector<std::string> fullJustify(std::vector<std::string>& words, int maxWidth) {
using namespace std;
int wordsBeginIndex = 0;
vector<string>result;
while (wordsBeginIndex<words.size())
{
int wordsEndIndex = wordsBeginIndex;
int rowLengthNow = 0;
int extraLengthAdder = 0;
while (wordsEndIndex<words.size()&& rowLengthNow+ words[wordsEndIndex].size()+ extraLengthAdder <=maxWidth)
{
rowLengthNow += words[wordsEndIndex].size();
if (wordsEndIndex != wordsBeginIndex) {
++rowLengthNow;//多计算一个绝对空格,题没说
}
extraLengthAdder = 1;
++wordsEndIndex;
}
int numberOfWords = wordsEndIndex - wordsBeginIndex;
int numberOfGap = max(1, numberOfWords - 1);
int totalGap = maxWidth - rowLengthNow+(numberOfWords-1);//加上多算的空格
cout << numberOfWords << ' ' << totalGap <<' '<< rowLengthNow<< endl;
string oneRow;
for (int i = wordsBeginIndex; i < wordsEndIndex; i++)
{
auto JustifyFull = [&]() {
oneRow += words[i];
if (i == wordsEndIndex - 1 && wordsEndIndex != wordsBeginIndex + 1) {//最后一个单词的处理
return;
}
for (int j = 0; j < totalGap / numberOfGap; j++)
{
oneRow += " ";
}
oneRow += totalGap % numberOfGap > (i - wordsBeginIndex) ? " " : "";
};
auto JustifyLeft = [&]() {
oneRow += words[i];
if (i == wordsEndIndex - 1 ) {//最后一个单词的处理
while (oneRow.size() < maxWidth)
oneRow += " ";
return;
}
oneRow += " ";
};
if (wordsEndIndex == words.size()) {//最后一行
JustifyLeft();//左对齐
}
else {
JustifyFull();
}
}
result.push_back(oneRow);
wordsBeginIndex = wordsEndIndex;
}
return result;
}
};//9 17-10 33=1H16M