68. Text Justification
Problem
Format words into lines of exactly maxWidth characters. Pack as many words per line as fit (greedily), then pad with spaces so each line is fully justified, giving extra spaces to the leftmost gaps first. The last line, and any line with a single word, is left-justified and padded with spaces on the right.
Example: ["This","is","an","example","of","text","justification."], maxWidth = 16 → ["This is an","example of text","justification. "]
Greedy line packing: a word fits if letters + len(word) + (number of words already on the line) ≤ maxWidth (one space minimum per gap). When the line is full, distribute maxWidth − letters spaces over the gaps round-robin from the left (left gaps get the extras); a single-word line is left-justified. The last line is left-justified and padded.
maxWidth 16: "This" "is" "an" letters 8, gaps 2, spaces 8 -> 4 + 4
"This is an"
"example of text" letters 13, gaps 2, spaces 3 -> 2 + 1
"justification. " last line: single spaces, pad right
Complexity: O(total characters).
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
res, line, letters = [], [], 0
for w in words:
if letters + len(w) + len(line) > maxWidth:
gaps = len(line) - 1 or 1
for i in range(maxWidth - letters):
line[i % gaps] += " "
res.append("".join(line))
line, letters = [], 0
line.append(w)
letters += len(w)
res.append(" ".join(line).ljust(maxWidth))
return res
assert Solution().fullJustify(["This", "is", "an", "example", "of", "text", "justification."], 16) == [
"This is an", "example of text", "justification. "]
assert Solution().fullJustify(["What", "must", "be", "acknowledgment", "shall", "be"], 16) == [
"What must be", "acknowledgment ", "shall be "]
assert Solution().fullJustify(["Science", "is", "what", "we", "understand", "well", "enough", "to", "explain",
"to", "a", "computer.", "Art", "is", "everything", "else", "we", "do"], 20) == [
"Science is what we", "understand well", "enough to explain to", "a computer. Art is",
"everything else we", "do "]
assert Solution().fullJustify(["a"], 1) == ["a"]
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new ArrayList<>();
int i = 0;
while (i < words.length) {
int j = i, letters = 0;
while (j < words.length && letters + words[j].length() + (j - i) <= maxWidth) letters += words[j++].length();
StringBuilder sb = new StringBuilder(words[i]);
int gaps = j - i - 1;
if (j == words.length || gaps == 0) { // last line or single word: left-justify
for (int k = i + 1; k < j; k++) sb.append(' ').append(words[k]);
sb.append(" ".repeat(maxWidth - sb.length()));
} else {
int spaces = maxWidth - letters, each = spaces / gaps, extra = spaces % gaps;
for (int k = i + 1; k < j; k++) sb.append(" ".repeat(each + (k - i <= extra ? 1 : 0))).append(words[k]);
}
res.add(sb.toString());
i = j;
}
return res;
}
}
func fullJustify(words []string, maxWidth int) []string {
res := []string{}
line, letters := []string{}, 0
for _, w := range words {
if letters+len(w)+len(line) > maxWidth { // w does not fit: justify the current line
gaps := max(len(line)-1, 1)
for i := 0; i < maxWidth-letters; i++ {
line[i%gaps] += " " // round-robin puts extra spaces on the left
}
res = append(res, strings.Join(line, ""))
line, letters = []string{}, 0
}
line = append(line, w)
letters += len(w)
}
last := strings.Join(line, " ") // the last line is left-justified
return append(res, last+strings.Repeat(" ", maxWidth-len(last)))
}