Similar Problems

Similar Problems not available

Text Justification - Leetcode Solution

LeetCode:  Text Justification Leetcode Solution

Difficulty: Hard

Topics: string array simulation  

The Text Justification problem on LeetCode asks you to take in a list of words and an integer value representing the maximum number of characters that can fit on one line. You have to divide the words into lines such that each line has at most the maximum width and is fully justified. The final output should be a list of strings, where each string represents a line in the text. The text should be fully justified, which means that the spaces between the words in each line should be evenly distributed.

To solve this problem, you can follow these steps:

Step 1: Divide the words into lines First, you need to divide the words into lines such that each line has at most the maximum width. You can do this by keeping track of the current line's word count and the current line's character count. Then, keep adding new words to the current line until the character count exceeds the maximum width. Once the maximum width is reached, start a new line and continue adding words to the new line until you run out of words.

Step 2: Fully justify each line Once you have divided the words into lines, the next step is to fully justify each line. To do this, you need to add extra spaces between the words in each line. The number of extra spaces you need to add between the words will depend on the following factors:

  • The total number of spaces left to fill in the line after adding the words
  • The number of gaps between the words in the line

To distribute the spaces evenly, you can calculate the total number of spaces needed to fill in the line by subtracting the current line's character count from the maximum width. Next, you need to calculate the total number of gaps between the words by counting the number of words in the line and subtracting one. Finally, you can distribute the spaces evenly among the gaps by dividing the total number of spaces by the number of gaps.

Step 3: Handle special cases There are a few special cases you need to handle. For example, if a line has only one word, you don't need to add any extra spaces between the words. Also, for the last line, you need to left-justify the text and not add any extra spaces at the end of the line.

Once you have followed these steps, you should have a fully justified text that meets the requirements of the Text Justification problem on LeetCode.

Text Justification Solution Code

1