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.
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> result;
// Case no words.
if(words.size() == 0) {
result.push_back(string(L, ' '));
return result;
}
int currentlength = 0;
int cur = 0;
while(cur < words.size()) {
// Find segment with start and end.
int start = cur;
int end = cur;
while(end < words.size() && currentlength + words[end].length() + end - start <= L) {
currentlength += words[end].length();
end ++;
}
// If this is the last one, break the loop.
if(end == words.size())
break;
// Make up string with words between start and end.
int wordnum = end - start;
int spacenum = L - currentlength;
string thisstr;
for(int ii = 0; ii < wordnum; ii ++) {
thisstr += words[start + ii];
if(spacenum == 0 || thisstr.length() == L)
continue;
if(wordnum == 1) {
thisstr += string(L - thisstr.length(), ' ');
break;
}
int spaces = spacenum / (wordnum - 1) + (spacenum % (wordnum - 1) > ii ? 1 : 0);
thisstr += string(spaces, ' ');
}
result.push_back(thisstr);
// Set new condition for loop.
cur = end;
currentlength = 0;
}
//Process the last one if exist.
if(cur < words.size()) {
string last;
while(cur < words.size()) {
last += words[cur ++];
if(last.size() < L)
last += ' ';
}
last += string(L - last.length(), ' ');
result.push_back(last);
}
return result;
}
};