description
给定长度L和一个字符串数组,使输出的每一行的长度固定为L,并尽可能多得放入字符串,每个字符串之间最少有一个空格,将空格均匀分布到字符串之间,如果不能均匀分布,将剩下的空格从左往右分布到字符串间
最后一行每个字符串之间空一个空格即可,最后用空格补齐
中间如果只能放一个字符,后面用空格补齐
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ‘ ‘ when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example,
words: [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
L: 16.
Return the formatted lines as:
Note: Each word is guaranteed not to exceed L in length.
思路
像这样的题目首先是将问题分解为多个小问题,然后一个一个解决
可以分为两个问题:
- 如果每个字符串之间最少一个空格,每行长度最大为L,那么字符串数组可以分为几行?
- 对第一步分好的行按照要求均匀分布空格
这样这道题做起来就很简单了,代码如下: