LeetCode Text Justification
LeetCode-solving Text Justification
Original question
Store the words in a set according to 1 character in each line. If there is not enough space to be added between words, the two ends of each line should be aligned (that is, both ends should be words ), if spaces cannot be evenly distributed across all intervals, the spaces on the left are more than those on the right, and the last line is aligned to the left. Each word has a space.
Note:
The order of words cannot be changed or there may be only one word in the middle. At this time, you must align the order to the left to accommodate as many words as possible.
Example:
Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
Output:
[ "This is an", "example of text", "justification. "]
Solutions
This question is complicated, and it is a big topic. The double pointer is used to mark the words in the current row. If the length of the next word is added and at least one space is used between each word, the total length is greater than the target length, this indicates that the word is stored in this row. Whether there is only one word or multiple words for discussion. If there are multiple words, We Need To evenly allocate spaces between words. Now we can know the total number of spaces and the word interval. Therefore, the calculation interval between words is relatively simple. Note that extra spaces should be added to the left-side word interval first. Do not forget to add words in the last line.
AC Source Code
class Solution(object): def fullJustify(self, words, maxWidth): """ :type words: List[str] :type maxWidth: int :rtype: List[str] """ start = end = 0 result, curr_words_length = [], 0 for i, word in enumerate(words): if len(word) + curr_words_length + end - start > maxWidth: if end - start == 1: result.append(words[start] + ' ' * (maxWidth - curr_words_length)) else: total_space = maxWidth - curr_words_length space, extra = divmod(total_space, end - start - 1) for j in range(extra): words[start + j] += ' ' result.append((' ' * space).join(words[start:end])) curr_words_length = 0 start = end = i end += 1 curr_words_length += len(word) result.append(' '.join(words[start:end]) + ' ' * (maxWidth - curr_words_length - (end - start - 1))) return resultif __name__ == "__main__": assert Solution().fullJustify(["This", "is", "an", "example", "of", "text", "justification."], 16) == [ "This is an", "example of text", "justification. " ]