68.文本左右对齐

文本左右对齐

给定一个单词数组 words 和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。

提示:

  • 1 <= words.length <= 300
  • 1 <= words[i].length <= 20
  • 1 <= maxWidth <= 100

解析

贪心 + 模拟:尽可能多放单词,然后均匀分配空格。

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
var fullJustify = function (words, maxWidth) {
const result = [];
let i = 0;
while (i < words.length) {
let j = i, lineLen = 0;
while (j < words.length && lineLen + words[j].length + (j - i) <= maxWidth) {
lineLen += words[j].length;
j++;
}
const gaps = j - i - 1;
let line = '';
if (j === words.length || gaps === 0) {
line = words.slice(i, j).join(' ');
line += ' '.repeat(maxWidth - line.length);
} else {
const spaces = maxWidth - lineLen;
const avg = Math.floor(spaces / gaps);
const extra = spaces % gaps;
for (let k = i; k < j; k++) {
line += words[k];
if (k < j - 1) line += ' '.repeat(avg + (k - i < extra ? 1 : 0));
}
}
result.push(line);
i = j;
}
return result;
};

68.文本左右对齐
https://leetcode.lz5z.com/68.text-justification/
作者
tickli
发布于
2023年11月25日
许可协议