|
| 1 | +/** |
| 2 | + * 68. Text Justification |
| 3 | + * https://leetcode.com/problems/text-justification/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an array of strings words and a width maxWidth, format the text such that each |
| 7 | + * line has exactly maxWidth characters and is fully (left and right) justified. |
| 8 | + * |
| 9 | + * You should pack your words in a greedy approach; that is, pack as many words as you |
| 10 | + * can in each line. Pad extra spaces ' ' when necessary so that each line has exactly |
| 11 | + * maxWidth characters. |
| 12 | + * |
| 13 | + * Extra spaces between words should be distributed as evenly as possible. If the number |
| 14 | + * of spaces on a line does not divide evenly between words, the empty slots on the left |
| 15 | + * will be assigned more spaces than the slots on the right. |
| 16 | + * |
| 17 | + * For the last line of text, it should be left-justified, and no extra space is inserted |
| 18 | + * between words. |
| 19 | + * |
| 20 | + * Note: |
| 21 | + * - A word is defined as a character sequence consisting of non-space characters only. |
| 22 | + * - Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. |
| 23 | + * - The input array words contains at least one word. |
| 24 | + */ |
| 25 | + |
| 26 | +/** |
| 27 | + * @param {string[]} words |
| 28 | + * @param {number} maxWidth |
| 29 | + * @return {string[]} |
| 30 | + */ |
| 31 | +var fullJustify = function(words, maxWidth) { |
| 32 | + const result = [[]]; |
| 33 | + result[0].count = 0; |
| 34 | + |
| 35 | + for (const word of words) { |
| 36 | + let row = result[result.length - 1]; |
| 37 | + if (row.length && row.count + row.length + word.length > maxWidth) { |
| 38 | + result.push([]); |
| 39 | + row = result[result.length - 1]; |
| 40 | + row.count = 0; |
| 41 | + } |
| 42 | + row.push(word); |
| 43 | + row.count += word.length; |
| 44 | + } |
| 45 | + |
| 46 | + for (let i = 0; i < result.length; i++) { |
| 47 | + const row = result[i]; |
| 48 | + if (row.length === 1 || i === result.length - 1) { |
| 49 | + result[i] = row.join(' ') + ' '.repeat(maxWidth - row.count - row.length + 1); |
| 50 | + continue; |
| 51 | + } |
| 52 | + |
| 53 | + const min = ' '.repeat(Math.floor((maxWidth - row.count) / (row.length - 1))); |
| 54 | + for (let j = 1; j < row.length; j++) { |
| 55 | + const delimiter = j <= (maxWidth - row.count) % (row.length - 1) ? ' ' : ''; |
| 56 | + row[0] += min + delimiter + row[j]; |
| 57 | + } |
| 58 | + |
| 59 | + result[i] = row[0]; |
| 60 | + } |
| 61 | + |
| 62 | + return result; |
| 63 | +}; |
0 commit comments