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
- ML | Text Summarization of links based on user query
- Process-based and Thread-based Multitasking
- Transforming a Plain Text message to Cipher Text
- Convert Text and Text File to PDF using Python
- CSS | border-top-width Property
- How to configure modal width in Bootstrap?
- How to change the width and height of Twitter Bootstrap's tooltips?
- Log based Recovery in DBMS
- Image based Steganography using Python
- Calculate weight of parenthesis based on the given conditions
- Construct the Cypher string based on the given conditions
- Sort an array of strings based on the given order
- Creating a simple JSON based API using Node.js
- Sort an array of strings lexicographically based on prefix
- Queue based approach for first non-repeating character in a stream
- Selecting rows in pandas DataFrame based on conditions
- Find time taken to execute the tasks in A based on the order of execution in B
- Building a terminal based online dictionary with Python and bash
- Sort the strings based on the numbers of matchsticks required to represent them
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.