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 Lcharacters.
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.
- 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.
I'm slow in handling these long description, so it's necessary to ask for an input/output case from the interview.
Another mistake is that I overview the last line "For the last line of text, it should be left justified and no extra space is inserted between words."
The following is the AC code :
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<string> res;
string row;
if (words.size() < 1)
return res;
int i = 0, j = 0, curlen = words[0].length(), wordstart = 0, largerspace, largerspacenum;
for (i = 1; i < words.size(); ++i) {
if (curlen + words[i].length() + 1 > L) {//extra space
row = words[wordstart];
if (i - 1- wordstart != 0) {
largerspace = (L - curlen) / (i - 1 - wordstart) + 2;//1 is for the counting ' '; the other 1 is for the divide
largerspacenum = (L - curlen) % (i - 1 - wordstart);
}
else{
largerspace = L - curlen;
for(int k = 0; k < largerspace; ++k)
row += ' ';
}
int spacecount = 1;
for (j = wordstart + 1; j <= i -1; ++j) {
int kk;
if (spacecount <= largerspacenum)
kk = largerspace;
else
kk = largerspace - 1;
for(int k = 0; k < kk; ++k)
row += ' ';
row += words[j];
++spacecount;
}
res.push_back(row);
curlen = words[i].length();
wordstart = i;
}
else
curlen += words[i].length() + 1;
}
row = "";
for (i = wordstart; i <= words.size() -1; ++i) {
row += words[i];
if (L > curlen)
row += ' ';
}
for (int k = 0; k < L - curlen - 1; ++k)
row += ' ';
res.push_back(row);
return res;
}
};