Given a string str and width of each line as L, the task is to justify the string such that each line of justified text is of length L with help of space (‘ ‘) and the last line should be left-justified.
Input: str = “GeeksforGeek is the best computer science portal for geeks.”, L = 16
Input: str = “The quick brown fox jumps over the lazy dog.”, L = 11
The symbol _ denotes a space.
The number of spaces between words in each line cannot be computed until a complete set of words in that line is known. We will solve this problem on a line-by-line basis.
- Split the given text into words
- Firstly select the words which can be inserted in each line including a space between each word. For that, the sum of length of included words with one space between them must be smaller than or equal to L.
- Now count the number of spaces needed to make the length of each line L and distribute the spaces evenly.
- Repeat above steps for next set of words.
- For the last line spaces must be assigned at the end as the last line must be left-justified.
Below is the implementation of the above approach:
GeeksforGeek is the best computer science portal for geeks.
Time Complexity: O(N), where N = length of string
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- CSS | text-justify Property
- Process-based and Thread-based Multitasking
- ML | Text Summarization of links based on user query
- Transforming a Plain Text message to Cipher Text
- Convert Text and Text File to PDF using Python
- Minimum element of each row and each column in a matrix
- Generate a String from given Strings P and Q based on the given conditions
- CSS | border-top-width Property
- How to configure modal width in Bootstrap?
- How to change the width and height of Twitter Bootstrap's tooltips?
- Sort an array of strings based on the given order
- Construct the Cypher string based on the given conditions
- Calculate weight of parenthesis based on the given conditions
- Generate a string from an array of alphanumeric strings based on given conditions
- Sum of indices of Characters removed to obtain an Empty String based on given conditions
- Building a terminal based online dictionary with Python and bash
- Queue based approach for first non-repeating character in a stream
- Log based Recovery in DBMS
- Image based Steganography using Python
- Selecting rows in pandas DataFrame based on conditions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.