跳至主要內容

68. 文本左右对齐


68. 文本左右对齐open in new window

🔴   🔖  数组 字符串 模拟  🔗 力扣open in new window LeetCodeopen in new window

题目

Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth 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 maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does 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.

Note:

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

Example 1:

Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16

Output:

[

"This is an",

"example of text",

"justification. "

]

Example 2:

Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16

Output:

[

"What must be",

"acknowledgment ",

"shall be "

]

Explanation: Note that the last line is "shall be> " instead of "shall> be", because the last line must be left-justified instead of fully-justified.

Note that the second line is also left-justified because it contains only one word.

Example 3:

Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20

Output:

[

"Science is what we",

"understand well",

"enough to explain to",

"a computer. Art is",

"everything else we",

"do "

]

Constraints:

  • 1 <= words.length <= 300
  • 1 <= words[i].length <= 20
  • words[i] consists of only English letters and symbols.
  • 1 <= maxWidth <= 100
  • words[i].length <= maxWidth

题目大意

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

你应该使用 “贪心算法” 来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。

要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。

文本的最后一行应为左对齐,且单词之间不插入额外的空格。

注意:

  • 单词是指由非空格字符组成的字符序列。
  • 每个单词的长度大于 0,小于等于 maxWidth
  • 输入单词数组 words 至少包含一个单词。

解题思路

  • 先计算出每一行可以放进去哪些单词,以及有几个空格
  • 再按照题目要求将单词和空格拼接好
  • 注意最后一行要特殊处理

代码

/**
 * @param {string[]} words
 * @param {number} maxWidth
 * @return {string[]}
 */
var fullJustify = function (words, maxWidth) {
	let res = [],
		count = 0,
		temp = [],
		space = [];
	for (let i = 0; i < words.length; i++) {
		let len = words[i].length;
		if (count + len > maxWidth) {
			res.push(temp);
			space.push(maxWidth - count + temp.length);
			temp = [];
			count = 0;
		}
		temp.push(words[i]);
		count += len + 1;
		if (i == words.length - 1) {
			res.push(temp);
			space.push(maxWidth - count + 1);
		}
	}

	for (let i = 0; i < res.length - 1; i++) {
		res[i] = mergeWords(res[i], space[i]);
	}
	res[res.length - 1] =
		res[res.length - 1].join(' ') +
		new Array(space[res.length - 1]).fill(' ').join('');

	return res;
};

var mergeWords = function (words, space) {
	const len = words.length - 1;
	if (len == 0) return words[0] + new Array(space).fill(' ').join('');
	const m = Math.floor(space / len);
	const spaceStr = new Array(m).fill(' ').join('');
	const n = space % len;
	if (n == 0) {
		return words.join(spaceStr);
	}
	return (
		words.slice(0, n).join(spaceStr + ' ') +
		spaceStr +
		' ' +
		words.slice(n, words.length).join(spaceStr)
	);
};

相关题目

题号标题题解标签难度
1592重新排列单词间的空格open in new window字符串
2138将字符串拆分为若干长度为 k 的组open in new window字符串 模拟
2468根据限制分割消息open in new window字符串 二分查找