68. 文本左右对齐
题目
描述:
给定一个单词数组 words 和一个长度 maxWidth ,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。
你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。
要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。
文本的最后一行应为左对齐,且单词之间不插入额外的空格。
注意:
- 单词是指由非空格字符组成的字符序列。
- 每个单词的长度大于 0,小于等于
maxWidth。 - 输入单词数组
words至少包含一个单词。
示例 1:
- 输入:
words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16 - 输出:
1 2 3 4 5
[ "This is an", "example of text", "justification. " ]
示例 2:
- 输入:
words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16 - 输出:
1 2 3 4 5
[ "What must be", "acknowledgment ", "shall be " ]
- 解释: 注意最后一行和只包含一个单词的行的格式。
示例 3:
- 输入:
words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20 - 输出:
1 2 3 4 5 6 7 8
[ "Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do " ]
提示:
1 <= words.length <= 3001 <= words[i].length <= 20words[i]由小写英文字母和符号组成1 <= maxWidth <= 100words[i].length <= maxWidth
题解
先确定一行包含哪些单词
本题可以按“选词”和“排版”两步处理。选词时,相邻单词先按一个空格计算宽度,从当前单词开始尽量向这一行加入后续单词;只有在整行单词范围确定后,才分配用于左右对齐的额外空格。
代码中的 lineLen 表示当前已选单词加上最少分隔空格后的长度。只要 lineLen + 1 + words[i].length() <= maxWidth,就能再加入一个单词。这符合题目要求的每行尽量多放单词。选完后,用左闭右开区间 [left, right) 表示本行单词,单词数量为 right - left,空隙数量 gaps 比单词数少 1。
根据行的类型分配空格
如果这是最后一行,或者这一行只有一个单词,就按左对齐处理:单词之间只放一个空格,剩下的空位全补到行尾。
其余的普通行要左右对齐。先把这一行所有单词本身的长度加起来,得到 wordsTotalLen,这一行需要补的空格总数就是 totalSpaces = maxWidth - wordsTotalLen。把它分给 gaps 个空隙:每个空隙先分到 totalSpaces / gaps 个(代码中的 avgSpaces),余下的 totalSpaces % gaps 个(extraSpaces)从左到右各补一个给前面的空隙。
拿题目里的 "example", "of", "text" 这一行看会很直观。三个单词长度一共是 7 + 2 + 4 = 13,maxWidth = 16,所以总共还要补 3 个空格。这一行有两个空隙,平均下来每个至少 1 个,还多出 1 个,所以左边空隙放 2 个空格,右边放 1 个,最后得到的就是 "example of text"。题目要求“左边的空隙更多”,其实正是通过这一步实现的。
最后一行即使有多个词间空隙,也必须按题目要求左对齐,不能套均分公式。只有一个单词的行则没有词间空隙,gaps = 0,必须避免除零。这两种情况都可以在拼完单词后,用空格把行尾补到 maxWidth。
普通行中,j - left 是当前空隙从 0 开始的编号。判断它是否小于 extraSpaces,就能让最左侧的若干空隙各多拿一个空格。最后一个单词之后不再追加词间空格,保证普通行左右两端都恰好是单词。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new ArrayList<>();
int n = words.length;
int i = 0;
while (i < n) {
int left = i;
int lineLen = words[i].length();
i++;
while (i < n && lineLen + 1 + words[i].length() <= maxWidth) {
lineLen += 1 + words[i].length();
i++;
}
int right = i;
int numWords = right - left;
int gaps = numWords - 1;
StringBuilder sb = new StringBuilder();
if (right == n || numWords == 1) {
for (int j = left; j < right; j++) {
if (j > left) {
sb.append(" ");
}
sb.append(words[j]);
}
while (sb.length() < maxWidth) {
sb.append(" ");
}
} else {
int wordsTotalLen = 0;
for (int j = left; j < right; j++) {
wordsTotalLen += words[j].length();
}
int totalSpaces = maxWidth - wordsTotalLen;
int avgSpaces = totalSpaces / gaps;
int extraSpaces = totalSpaces % gaps;
for (int j = left; j < right - 1; j++) {
sb.append(words[j]);
for (int k = 0; k < avgSpaces; k++) {
sb.append(" ");
}
if (j - left < extraSpaces) {
sb.append(" ");
}
}
sb.append(words[right - 1]);
}
res.add(sb.toString());
}
return res;
}
设所有单词字符总数为 S,输出总字符数为 R。时间为 O(S + R),不计返回结果,当前行的构造缓冲区占 O(maxWidth) 辅助空间。
完整示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new ArrayList<>();
int n = words.length;
int i = 0;
while (i < n) {
int left = i;
int lineLen = words[i].length();
i++;
while (i < n && lineLen + 1 + words[i].length() <= maxWidth) {
lineLen += 1 + words[i].length();
i++;
}
int right = i;
int numWords = right - left;
int gaps = numWords - 1;
StringBuilder sb = new StringBuilder();
if (right == n || numWords == 1) {
for (int j = left; j < right; j++) {
if (j > left) {
sb.append(" ");
}
sb.append(words[j]);
}
while (sb.length() < maxWidth) {
sb.append(" ");
}
} else {
int wordsTotalLen = 0;
for (int j = left; j < right; j++) {
wordsTotalLen += words[j].length();
}
int totalSpaces = maxWidth - wordsTotalLen;
int avgSpaces = totalSpaces / gaps;
int extraSpaces = totalSpaces % gaps;
for (int j = left; j < right - 1; j++) {
sb.append(words[j]);
for (int k = 0; k < avgSpaces; k++) {
sb.append(" ");
}
if (j - left < extraSpaces) {
sb.append(" ");
}
}
sb.append(words[right - 1]);
}
res.add(sb.toString());
}
return res;
}
public static void main(String[] args) {
String[] words1 = {"This", "is", "an", "example", "of", "text", "justification."};
int maxWidth1 = 16;
System.out.println("示例 1 输出:");
printResult(fullJustify(words1, maxWidth1));
System.out.println("-----------------------------");
String[] words2 = {"What", "must", "be", "acknowledgment", "shall", "be"};
int maxWidth2 = 16;
System.out.println("示例 2 输出:");
printResult(fullJustify(words2, maxWidth2));
System.out.println("-----------------------------");
String[] words3 = {"Science", "is", "what", "we", "understand", "well", "enough", "to", "explain", "to", "a", "computer.", "Art", "is", "everything", "else", "we", "do"};
int maxWidth3 = 20;
System.out.println("示例 3 输出:");
printResult(fullJustify(words3, maxWidth3));
}
private static void printResult(List<String> result) {
for (String line : result) {
System.out.println("\"" + line + "\"");
}
}
}
运行结果(OpenJDK 21.0.12):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
示例 1 输出:
"This is an"
"example of text"
"justification. "
-----------------------------
示例 2 输出:
"What must be"
"acknowledgment "
"shall be "
-----------------------------
示例 3 输出:
"Science is what we"
"understand well"
"enough to explain to"
"a computer. Art is"
"everything else we"
"do "
