68. Text Justification
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]Last updated
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]Last updated
Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
"What must be",
"acknowledgment ",
"shall be "
]
Explanation: Note that the last line is "shall be " instead of "shall be",
because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified becase it contains only one word.Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
"to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]vector<string> fullJustify(vector<string>& words, int maxWidth) { // time: O(n^2); space: O(n^2)
int n = words.size();
vector<string> res;
int word_num; // # of words in the current line
for (int start_idx = 0; start_idx < n; start_idx += word_num) {
int curWidth = 0;
// calculate word_num in the current line
for (word_num = 0; start_idx + word_num < n && curWidth + words[start_idx + word_num].length() <= maxWidth - word_num; ++word_num) {
curWidth += words[start_idx + word_num].length();
}
string cur = words[start_idx];
// pad spaces between words
for (int interval_idx = 0; interval_idx < word_num - 1; ++interval_idx) {
if (start_idx + word_num == n) cur += " "; // last line
else {
int space = (maxWidth - curWidth) / (word_num - 1);
int extra = (maxWidth - curWidth) % (word_num - 1);
cur += string(space + (extra > interval_idx), ' ');
}
cur += words[start_idx + interval_idx + 1]; // add the next word
}
// last line or only one word in the current line
cur += string(maxWidth - cur.length(), ' ');
res.push_back(cur);
}
return res;
}