68. Text Justification 🔄
Difficulty: Hard - Tags: String, Greedy
Description
Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth 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 maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does 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.
Examples
Example 1:
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16Output:
[
"This is an",
"example of text",
"justification. "
]Example 2:
Input:
Output:
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.
Example 3:
Input:
Output:
Constraints
The input array
wordscontains at least one word.Each word's length is guaranteed to be greater than 0 and not exceed
maxWidth.
Solution 💡
In this solution, we use a greedy approach to pack words into each line, ensuring that the line length does not exceed maxWidth. When the line is full, we justify the text by adding extra spaces between words. If the line contains only one word, we pad the remaining space with spaces.
Java
Time Complexity ⏳
O(n): We iterate through the list of words once, processing each word in constant time to fit it into a line.
Space Complexity 💾
O(n): The space complexity is linear, where
nis the total number of characters in the input list of words and in the result.
You can find the full solution here.
Last updated
Was this helpful?