Given an array of words and a length L, format the text such that each line has exactlyL 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> ret;
int start = 0, end = 0;
int curLen = 0;
if (L == 0) {
ret.push_back("");
return ret;
}
curLen = words[0].length();
for (int i = 1; i < words.size(); ++i) {
if (curLen + words[i].length() + 1 > L) {
ret.push_back(oneLineJustify(words, L, start, end, curLen));
start = i;
end = i;
curLen = words[i].length();
} else {
curLen += words[i].length();
end = i;
if (start != end) ++curLen;
}
}
ret.push_back(lastLineJustify(words, L, start, end, curLen));
return ret;
}
string oneLineJustify(vector<string> &words, int L, int start, int end, int curLen) {
string ret;
int numSpaces = end - start;
int lenSpaces = 0;
if (numSpaces == 0) {
ret.append(words[start]);
ret.append(L-words[start].length(), ' ');
} else {
ret.append(words[start]);
lenSpaces = (L - curLen) / numSpaces;
for (int i = 0; i < numSpaces; ++i) {
if (i < (L - curLen) % numSpaces) {
ret.append(lenSpaces+2, ' ');
} else {
ret.append(lenSpaces+1, ' ');
}
ret.append(words[start + i + 1]);
}
}
return ret;
}
string lastLineJustify(vector<string> &words, int L, int start, int end, int curLen) {
string ret;
ret.append(words[start]);
for (int i = start + 1; i <= end; ++i) {
ret.append(1, ' ');
ret.append(words[i]);
}
ret.append(L-curLen, ' ');
return ret;
}
};