# LeetCode题目：Text Justification

By | 2012 年 10 月 31 日

Text Justification
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.”]
L: 16.
Return the formatted lines as:
[
“This is an”,
“example of text”,
“justification. ”
]
Note: Each word is guaranteed not to exceed L in length.
Corner Cases:
A line other than the last line might contain only one word. What should you do in this case?
In this case, that line should be left-justified.

```class Solution {
public:
vector fullJustify(vector &words, int L) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector rslt;
if(0 == words.size()) return rslt;
int si = 0, ei = si;
int len = 0;
while(true) {
for(ei = si; ei < words.size(); ++ei) {
if(len + (ei - si) + words[ei].size() > L) {
break;
}
len += words[ei].size();
}
--ei;
if(ei < si) ei = si;
//form the string
if(si >= ei) {
//only one word on this line
string line = words[si];
line.append(L - line.size(), ' ');
rslt.push_back(line);
} else {
//multiple words on this line
bool lastline = (ei == (words.size() - 1));
int spaceBase = (L - len) / (ei - si);
int bonus = (L - len) - spaceBase * (ei - si);
if(lastline) {
//lastline
spaceBase = 1;
bonus = 0;
}
string line = words[si];
for(int i = si + 1; i <= ei; ++i) {
int space = spaceBase;
if(bonus > 0) {
++space;
--bonus;
}
line.append(space,' ');
line.append(words[i]);
}
if(lastline) {
line.append(L - len - ei + si,' ');
}
rslt.push_back(line);
}
//progress
si = ei + 1;
len = 0;
if(si >= words.size()) break;
}//end while
return rslt;
}
};
```