Will format the string such that each line has exactly (max_width) characters and is fully (left and right) justified, and return the list of justified text. example 1: string = "This is an example of text justification." max_width = 16 output = ['This is an',
(word: str, max_width: int)
| 1 | def text_justification(word: str, max_width: int) -> list: |
| 2 | """ |
| 3 | Will format the string such that each line has exactly |
| 4 | (max_width) characters and is fully (left and right) justified, |
| 5 | and return the list of justified text. |
| 6 | |
| 7 | example 1: |
| 8 | string = "This is an example of text justification." |
| 9 | max_width = 16 |
| 10 | |
| 11 | output = ['This is an', |
| 12 | 'example of text', |
| 13 | 'justification. '] |
| 14 | |
| 15 | >>> text_justification("This is an example of text justification.", 16) |
| 16 | ['This is an', 'example of text', 'justification. '] |
| 17 | |
| 18 | example 2: |
| 19 | string = "Two roads diverged in a yellow wood" |
| 20 | max_width = 16 |
| 21 | output = ['Two roads', |
| 22 | 'diverged in a', |
| 23 | 'yellow wood '] |
| 24 | |
| 25 | >>> text_justification("Two roads diverged in a yellow wood", 16) |
| 26 | ['Two roads', 'diverged in a', 'yellow wood '] |
| 27 | |
| 28 | Time complexity: O(m*n) |
| 29 | Space complexity: O(m*n) |
| 30 | """ |
| 31 | |
| 32 | # Converting string into list of strings split by a space |
| 33 | words = word.split() |
| 34 | |
| 35 | def justify(line: list, width: int, max_width: int) -> str: |
| 36 | overall_spaces_count = max_width - width |
| 37 | words_count = len(line) |
| 38 | if len(line) == 1: |
| 39 | # if there is only word in line |
| 40 | # just insert overall_spaces_count for the remainder of line |
| 41 | return line[0] + " " * overall_spaces_count |
| 42 | else: |
| 43 | spaces_to_insert_between_words = words_count - 1 |
| 44 | # num_spaces_between_words_list[i] : tells you to insert |
| 45 | # num_spaces_between_words_list[i] spaces |
| 46 | # after word on line[i] |
| 47 | num_spaces_between_words_list = spaces_to_insert_between_words * [ |
| 48 | overall_spaces_count // spaces_to_insert_between_words |
| 49 | ] |
| 50 | spaces_count_in_locations = ( |
| 51 | overall_spaces_count % spaces_to_insert_between_words |
| 52 | ) |
| 53 | # distribute spaces via round robin to the left words |
| 54 | for i in range(spaces_count_in_locations): |
| 55 | num_spaces_between_words_list[i] += 1 |
| 56 | aligned_words_list = [] |
| 57 | for i in range(spaces_to_insert_between_words): |
| 58 | # add the word |
| 59 | aligned_words_list.append(line[i]) |
| 60 | # add the spaces to insert |