Created
April 1, 2022 02:47
-
-
Save fullstackzach/8dc402e144a12b9ef355e0a0297c5094 to your computer and use it in GitHub Desktop.
My solution for https://leetcode.com/problems/text-justification/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string[]} words | |
* @param {number} maxWidth | |
* @return {string[]} | |
*/ | |
var fullJustify = function(words, maxWidth) { | |
let wordIndex = 0 | |
let justified = [] | |
let wordLengths = [] | |
while (wordIndex < words.length) { | |
// get array of words that will fit | |
let [fitWords, wordsLength] = getFittingWords(words, wordIndex, maxWidth) | |
wordIndex += fitWords.length | |
justified.push(buildLine(fitWords, wordsLength, maxWidth, wordIndex - 1 === words.length - 1)) | |
} | |
return justified | |
}; | |
function buildLine(fittingWords, wordsLength, maxWidth, isLast) { | |
let line = '' | |
let numSpaces = maxWidth - wordsLength | |
let isEvenSpaces = numSpaces % (fittingWords.length - 1) === 0 | |
if (isLast || fittingWords.length === 1) { | |
// left justify | |
// console.log(isLast, fittingWords) | |
for (let i = 0; i < fittingWords.length; i++) { | |
if (i === fittingWords.length - 1) { | |
line += fittingWords[i] | |
line += " ".repeat(maxWidth - line.length) | |
} else { | |
line += fittingWords[i] + " " | |
} | |
} | |
} else if (isEvenSpaces) { | |
let spaces = numSpaces / (fittingWords.length - 1) | |
for (let i = 0; i < fittingWords.length; i++) { | |
if (i === fittingWords.length - 1) { // last | |
line += fittingWords[i] | |
} else { | |
line += fittingWords[i] + " ".repeat(spaces) | |
} | |
} | |
} else { | |
let spaces = Math.floor((numSpaces) / (fittingWords.length - 1)) | |
let remainder = (numSpaces) % (fittingWords.length - 1) | |
console.log(fittingWords, spaces, remainder, wordsLength, maxWidth) | |
for (let i = 0; i < fittingWords.length; i++) { | |
if (i === fittingWords.length - 1) { // last | |
line += fittingWords[i] | |
} else { | |
line += fittingWords[i] + " ".repeat(spaces) | |
if (remainder > 0) { | |
line += " " | |
remainder--; | |
} | |
} | |
} | |
} | |
return line | |
} | |
// use recursion to get words from "words" that will fit, with one space between | |
function getFittingWords(words, i, widthRemaining, fittingWords = [], wordsLength = 0) { | |
if (!words[i] || words[i].length > widthRemaining) return [fittingWords, wordsLength] | |
if (words[i].length !== widthRemaining) { | |
widthRemaining--; | |
} | |
fittingWords.push(words[i]) | |
wordsLength += words[i].length | |
return getFittingWords(words, i + 1, widthRemaining - words[i].length, fittingWords, wordsLength) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment