68.文本左右对齐
链接:68.文本左右对齐
难度:Hard
标签:数组、字符串、模拟
简介:给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。
题解 1 - typescript
- 编辑时间:2021-09-09
- 执行用时:76ms
- 内存消耗:39.4MB
- 编程语言:typescript
- 解法介绍:逐个分解单词组进行拼接。
function repeat(len: number) {
  return ''.padEnd(len, ' ');
}
function fullJustify(words: string[], maxWidth: number): string[] {
  let idx = 0;
  const ans: string[] = [];
  const n = words.length;
  while (idx < n) {
    let len = 0;
    const list: string[] = [];
    while (idx < n && len + words[idx].length <= maxWidth) {
      const str = words[idx];
      len += str.length + 1;
      list.push(str);
      idx++;
    }
    if (idx === n) {
      ans.push(list.join(' ').padEnd(maxWidth, ' '));
    } else if (list.length === 1) {
      ans.push(list[0].padEnd(maxWidth, ' '));
    } else {
      const strlen = list.join('').length;
      let empty = maxWidth - strlen;
      const emptyList: number[] = new Array(list.length - 1).fill(0);
      for (let i = 0; empty !== 0; i = (i + 1) % (list.length - 1)) {
        emptyList[i]++;
        empty--;
      }
      let str = '';
      for (let i = 0; i < list.length; i++) {
        str += list[i] + repeat(emptyList.shift()!);
      }
      ans.push(str);
    }
  }
  return ans;
}