LeetCode 68. Text Justification题目解析-wowAC

Description

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words["This", "is", "an", "example", "of", "text", "justification."]
L16.

Return the formatted lines as:

[
"This    is    an",
"example  of text",
"justification.  "
]

Note: Each word is guaranteed not to exceed L in length.

class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int i = 0, j = -1, width = 0;
vector<string> res;

while(1) {
//计算每行可以安排的单词的区间 [i, j]
while(j+1<words.size()) {
if(width+words[j+1].length()+j+1-i <= maxWidth) {
width += words[j+1].length();
j++;
}else
break;
}

if(i > j) break;   //可以安排0个单词，即所有单词安排完毕

string line = "";
if(j == words.size()-1) {  //最后一行
for(int k=i; k<=j; k++) {
line += words[k];
if(k == j) continue;
line += ' ';
}
}else { //非最后一行
int space = maxWidth - width, base, extra;
if(i != j) {  //行内单词数大于1
base = space / (j-i);
extra = space % (j-i);
}
for(int k=i; k<=j; k++) {
line += words[k];
if(k==j) continue;
line += string(base, ' ');
if(extra> 0) {
line += " ";
extra--;
}
}

}
line += string(maxWidth - line.length(), ' ');
//cout<<line<<" "<<line.length()<<endl;
res.push_back(line);
i = j+1; j = i-1;
width = 0;
}
return res;
}
};