注意最后一行和只有一个word的行的特殊处理。
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> result;
if(words.size() == 0) return result;
int start = 0;
int wordsLength = 0;
for(int i=0; i<words.size(); i++)
{
if(wordsLength + words[i].size() + i-start > L)
{
string line = getLine(words, start, i-1, L, wordsLength, false);
result.push_back(line);
start = i;
wordsLength = 0;
}
wordsLength += words[i].size();
}
string line = getLine(words, start, words.size()-1, L, wordsLength, true);
result.push_back(line);
return result;
}
string getLine(vector<string> &words, int begin, int end, int L, int wordsLength, bool lastLine)
{
string line;
int count = end-begin+1;
if(!lastLine && count > 1)
{
int spaceLength = L-wordsLength;
int spaceEach = spaceLength/(count-1);
int left = spaceLength%(count-1);
for(int i=0; i<count; i++)
{
line += words[begin+i];
if(i < left)
line.insert(line.end(), spaceEach+1, ' ');
else if(i < count-1)
line.insert(line.end(), spaceEach, ' ');
}
}
else
{
for(int i=0; i<count; i++)
{
line += words[begin+i];
if(i<count-1)
line += " ";
else
line.insert(line.end(), L-line.size(), ' ');
}
}
return line;
}
};