LeetCode 68 Text Justification (Tag:Array Difficulty:Hard)

190 阅读3分钟

这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战

前言

关于 LeetCode 数组类型题目的相关解法,可见LeetCode 数组类型题目做前必看,分类别解法总结了题目,可以用来单项提高。觉得有帮助的话,记得多多点赞关注哦,感谢!

题目描述

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

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

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

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

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

示例:
输入:
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                  "
]

链接:leetcode-cn.com/problems/te…

题解

本题更像是平常我们业务中会碰到的需求, 要求你来对文字排版. 题目理解下来是给定每行最长字母长度, 依次填入给定的单词, 需要把每行填满, 单词之间用空格隔开.

主要是空格的处理, 假设能够放入的单词个数为 n, 那么至少需要 n - 1 个空格来隔开. 假设减去单词长度后剩余的长度为 m. 如果剩余空格个数大于 n - 1, 即 m > n - 1, 那么分配的策略是, 在减去 n - 1 的空格之后, 剩余的空格数如果能平分在 n - 1 个空格里, 则每个空格的长度为 1 + (m - n - 1) / n - 1. 如果不能平分, 则每个空格长度为 1 + Math.floor((m - n - 1) / n - 1), 这时候还剩下不足 n - 1 个空格, 将从左到右分配在每个单词右边.

特殊情况是最后一行, 最后一行的每个单词间隔只有一个,还要记得补足空格到规定字符数.

可以结合下图和代码来理解这个思路.(本题解法思路和下图均来自于:leetcode-cn.com/problems/te…)

image.png

/**
 * @param {string[]} words
 * @param {number} maxWidth
 * @return {string[]}
 */
var fullJustify = function(words, maxWidth) {
    let ans = []
    let cnt = 0
    let begin = 0
    const len = words.length
    for (let i = 0; i < words.length; i++) {
        cnt += words[i].length + 1 // 每次默认加上右边一个空格间隙
        
        // 如果为最后一个单词 或者 加上下一个单词长度大于了最大长度就开始排版
        if ((i+1) ===  len || cnt + words[i+1].length > maxWidth) {
            ans.push(fillWords(words, begin, i, maxWidth, i + 1 == len))
            begin = i + 1
            cnt = 0
        }
    }
    return ans
};

// begin 和 end 代表这次排版的单词下边开始和结束, isLast 代表是不是最后一行
const fillWords = (words, begin, end, maxWidth, isLast) => {
    const wordCount = end - begin + 1
    let spaceCount = maxWidth + 1 - wordCount // 空格占用字符数
    for (let i = begin; i <= end; i++) spaceCount -= words[i].length
    const spaceSuffix = 1 // 默认单个空格
    const spaceAvg = (wordCount == 1) ? 0 : Math.floor(spaceCount / (wordCount - 1)); // 减去默认空格后,每个空格增加的字符数
    const spaceExtra = (wordCount == 1) ? 0 : Math.floor(spaceCount % (wordCount - 1)); // 从左到右空格再增加1个的空格数
    
    let res = ''
    for (let i = begin; i < end; i++) {
        res += words[i]
        // 最后一行特殊处理
        if (isLast) {
            res += ' '
            continue
        }
        // n 代表真正的空格数
        let n = spaceSuffix + spaceAvg + (i - begin < spaceExtra ? 1 : 0)
        res += ' '.repeat(n)
    }
    res += words[end]
    // 用空格补齐不足的字符数, 只有最后一行和一行只有一个单词需要补齐
    res = res.padEnd(maxWidth, ' ')
    return res
}