同步操作将从 编程语言算法集/Python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
def text_justification(word: str, max_width: int) -> list:"""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 = 16output = ['This is an','example of text','justification. ']>>> text_justification("This is an example of text justification.", 16)['This is an', 'example of text', 'justification. ']example 2:string = "Two roads diverged in a yellow wood"max_width = 16output = ['Two roads','diverged in a','yellow wood ']>>> text_justification("Two roads diverged in a yellow wood", 16)['Two roads', 'diverged in a', 'yellow wood ']Time complexity: O(m*n)Space complexity: O(m*n)"""# Converting string into list of strings split by a spacewords = word.split()def justify(line: list, width: int, max_width: int) -> str:overall_spaces_count = max_width - widthwords_count = len(line)if len(line) == 1:# if there is only word in line# just insert overall_spaces_count for the remainder of linereturn line[0] + " " * overall_spaces_countelse:spaces_to_insert_between_words = words_count - 1# num_spaces_between_words_list[i] : tells you to insert# num_spaces_between_words_list[i] spaces# after word on line[i]num_spaces_between_words_list = spaces_to_insert_between_words * [overall_spaces_count // spaces_to_insert_between_words]spaces_count_in_locations = (overall_spaces_count % spaces_to_insert_between_words)# distribute spaces via round robin to the left wordsfor i in range(spaces_count_in_locations):num_spaces_between_words_list[i] += 1aligned_words_list = []for i in range(spaces_to_insert_between_words):# add the wordaligned_words_list.append(line[i])# add the spaces to insertaligned_words_list.append(num_spaces_between_words_list[i] * " ")# just add the last word to the sentencealigned_words_list.append(line[-1])# join the aligned words list to form a justified linereturn "".join(aligned_words_list)answer = []line: list[str] = []width = 0for inner_word in words:if width + len(inner_word) + len(line) <= max_width:# keep adding words until we can fill out max_width# width = sum of length of all words (without overall_spaces_count)# len(inner_word) = length of current inner_word# len(line) = number of overall_spaces_count to insert between wordsline.append(inner_word)width += len(inner_word)else:# justify the line and add it to resultanswer.append(justify(line, width, max_width))# reset new line and new widthline, width = [inner_word], len(inner_word)remaining_spaces = max_width - width - len(line)answer.append(" ".join(line) + (remaining_spaces + 1) * " ")return answerif __name__ == "__main__":from doctest import testmodtestmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。