LeetCode-68-文本左右对齐
in LeetCode with 0 comment

LeetCode-68-文本左右对齐

in LeetCode with 0 comment

原题地址:文本左右对齐

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

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

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

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

说明:

示例:

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

解答

根据每一行的最大长度先计算出能容纳的最大单词数量,注意每个单词间最少要有一个空格。然后根据单词数量计算出单词之间的空格数量,如果空格不能平均分配,剩余的就从前往后依次分配。再根据计算得到的空格数量和单词数量拼接出每一行的字符串即可。

具体的实现代码如下:

/**
 * @param {string[]} words
 * @param {number} maxWidth
 * @return {string[]}
 */
const fullJustify1 = function(words, maxWidth) {
    let i = 0; // 每一行开始的单词所在位置
    let result = []; // 结果集
    while (i < words.length) {
        // 当前行中单词的长度之和
        let length = 0; 
        // 记录当前行中最后一个单词的位置
        let j = i; 
        // 如果加上下一个单词会超过maxWidth,则不加上
        // 注意前面加入过的单词之间至少要间隔一个空格
        while (j < words.length && length + words[j].length + j - i <= maxWidth) {
            length += words[j].length;
            j ++;
        }
        // j当前指向了下一行的开头,退回来
        j --; 
        if (j === i) { 
            // 只有一个单词,左对齐
            result.push(words[i] + ' '.repeat(maxWidth - length));
        } else if (j === words.length - 1) { 
            // 最后一行,也是左对齐
            result.push(words.slice(i).join(' ') + ' '.repeat(maxWidth - length - (j - i)))
        } else { 
            // 处理需要左右对齐的行
            // 加入第一个单词
            let line = words[i]; 
            // 计算每两个单词中间最少空格数
            let blankCount = Math.floor((maxWidth - length)/(j - i)); 
            // 平均分配完成后剩余的空格数
            let remainingBlanks = maxWidth - length - blankCount * (j - i); 
            // 逐词处理
            for (let k = 1; k <= j - i; k ++) {
                // 先加空格,注意还有剩余空格时要从前往后每个位置分一个,直到分完
                line += ' '.repeat(k <= remainingBlanks ? blankCount + 1 : blankCount);
                // 加上对应的单词
                line += words[i + k];
            }
            result.push(line);
        }
        i = j + 1; // 处理下一行
    }
    return result;
};

测试:

let start = new Date();
const test = fullJustify1;
// [ 'This    is    an', 'example  of text', 'justification.  ' ]
console.log(test(["This", "is", "an", "example", "of", "text", "justification."], 16));
// [ 'What   must   be', 'acknowledgment  ', 'shall be        ' ]
console.log(test(["What","must","be","acknowledgment","shall","be"], 16));
/**
[
  'Science  is  what we',
  'understand      well',
  'enough to explain to',
  'a  computer.  Art is',
  'everything  else  we',
  'do                  '
]
 */
console.log(test(["Science","is","what","we","understand","well","enough","to","explain",
    "to","a","computer.","Art","is","everything","else","we","do"], 20));
console.log(new Date().getTime() - start.getTime()); // 11

时间复杂度: 计算每行单词数量时需要一次遍历,逐行处理时需要再一次遍历,时间复杂度为$O(N)$
空间复杂度: 需要一个数组来存放结果集,空间复杂度为$O(N)$