贪心算法相关问题
使用贪心算法解决--文本左右对齐【leetcode-68】
题目描述
给定一个单词数组 words 和一个长度 maxWidth ,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。
你应该使用 “贪心算法” 来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。
要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。
文本的最后一行应为左对齐,且单词之间不插入额外的空格。
运行效率
代码如下
function fullJustify(words: string[], maxWidth: number): string[] {
let resStrs = [];
let queue = [];
let tlen = -1;
let index = 0;
while (index < words.length) {
if (tlen + words[index].length + 1 <= maxWidth) {
queue.push(words[index]);
tlen = tlen + words[index++].length + 1;
} else {
const spaceCount = maxWidth - tlen + queue.length - 1;
if (queue.length === 1)
resStrs.push(queue.pop() + getBaseSpaceStr(spaceCount));
else {
const baseSpaceStr = getBaseSpaceStr(spaceCount / (queue.length - 1));
let more = spaceCount % (queue.length - 1);
resStrs.push(
queue.reduce((acc, curr, ti) => {
return (
acc + (ti - 1 < more ? baseSpaceStr + " " : baseSpaceStr) + curr
);
})
);
}
queue = [words[index]];
tlen = words[index++].length;
}
}
resStrs.push(queue.join(" ") + getBaseSpaceStr(maxWidth - tlen));
return resStrs;
function getBaseSpaceStr(len) {
len = Math.floor(len);
let str = "";
for (let i = 0; i < len; i++) {
str += " ";
}
return str;
}
}
const res2 = fullJustify(
["What", "must", "be", "acknowledgment", "shall", "be"],
16
);