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.
[Solution]
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> res;
int len = 0, start = 0, end = 0;
while(end < words.size()){
// try to add a word
if(start == end){
len = words[end].length();
}
else{
len = len + 1+ words[end].length();
}
// full
if(len == L){
// generate line
string line = words[start];
for(int i = start+1; i <= end; ++i){
line += " " + words[i];
}
res.push_back(line);
// update end
end++;
start = end;
}
// over flow
else if(len > L){
if(end - start == 1){
string line = words[start] + string(L - words[start].length(), ' ');
res.push_back(line);
}
else{
// get words length
len = 0;
for(int i = start; i <= end-1; ++i){
len += words[i].length();
}
// number of spaces in this line
int space = L - len;
// number of spaces between two words
int average = space / (end - start - 1);
int more = space % (end - start - 1);
// generate line
string line = words[start];
for(int i = start+1; i <= end-1; ++i){
if(i - start <= more){
line += string(average+1, ' ') + words[i];
}
else{
line += string(average, ' ') + words[i];
}
}
res.push_back(line);
}
start = end;
}
else{
end++;
}
}
// be careful to add the last line
if(end > 0 && start < words.size()){
string line = words[start];
for(int i = start+1; i < end; ++i){
line += " " + words[i];
}
// fill spaces
line += string(L - line.length(), ' ');
res.push_back(line);
}
return res;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客