题目
给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。
你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' '
填充,使得每行恰好有 maxWidth 个字符。
要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。
文本的最后一行应为左对齐,且单词之间不插入额外的空格。
说明:
- 单词是指由非空格字符组成的字符序列。
- 每个单词的长度大于 0,小于等于 maxWidth。
- 输入单词数组
words
至少包含一个单词。
示例1:
输入:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
输出:
[
"This is an",
"example of text",
"justification. "
]
示例 2:
输入:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
输出:
[
"What must be",
"acknowledgment ",
"shall be "
]
解释: 注意最后一行的格式应为 "shall be " 而不是 "shall be",
因为最后一行应为左对齐,而不是左右两端对齐。
第二行同样为左对齐,这是因为这行只包含一个单词。
示例 3:
输入:
words = ["Science","is","what","we","understand","well","enough","to","explain",
"to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
输出:
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]
思路
这题关键在于判断每行最多能放几个单词,注意不能单纯的只将单吃长度累加,再与 maxWidth 比较,因为单词之间还需要一个空格分隔,顾累加的过程中需要将空格分隔考虑在内;
再者就是空格平均分配的问题,例如11个空格,需要均分成3份,则先求出 11/3 = 3
,再求出 11%3=2
,将余下的2个分别放到第1份和第2份,就得到 4,4,3
;
代码如下:
代码
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> ans = new ArrayList<>();
int i = 0, j = 0, cnt = 0, len = words.length;
while (j < len) {
int t = cnt + words[j].length();
if (j != i)
t++;
if (t <= maxWidth) {
cnt = t;
j++;
} else {
StringBuilder sb = new StringBuilder();
if (j-i-1 == 0) {
int a = maxWidth-cnt;
sb.append(words[i]);
while (a-- > 0) sb.append(' ');
} else {
int a = maxWidth-cnt, b;
b = a%(j-i-1);
a /= (j-i-1);
sb.append(words[i]);
for (int p=i+1; p<j; p++){
sb.append(' ');
for (int q=0; q<a; q++) sb.append(' ');
if (b > 0){
sb.append(' ');
b--;
}
sb.append(words[p]);
}
}
i = j;
cnt = 0;
ans.add(sb.toString());
}
}
StringBuilder sb1 = new StringBuilder();
sb1.append(words[i]);
for (int p=i+1; p<j; p++)
sb1.append(' ').append(words[p]);
int a1 = maxWidth-cnt;
while (a1-- > 0) sb1.append(' ');
ans.add(sb1.toString());
return ans;
}
public static void main(String[] args) {
Solution solution = new Solution();
String[] a = {"Science","is","what","we","understand","well","enough","to","explain", "to","a","computer.","Art","is","everything","else","we","do"};
int b = 20;
List<String> ans = solution.fullJustify(a, b);
ans.forEach(System.out::println);
}
}