1
/**
2
* @param {string[]} words
3
* @param {number} maxWidth
4
* @return {string[]}
5
*/
6
var fullJustify = function (words, maxWidth) {
7
if (!words || !words.length) return;
8

9
const wordRows = [];
10
let wordCols = [];
11
let count = 0;
12
words.forEach((word, i) => {
13
if (count + word.length + wordCols.length > maxWidth) {
14
wordRows.push(wordCols);
15
wordCols = [];
16
count = 0;
17
}
18

19
wordCols.push(word);
20
count += word.length;
21

22
if (i === words.length - 1) {
23
wordRows.push(wordCols);
24
}
25
});
26

27
return wordRows.map((rowWords, i) =>
28
justifyText(rowWords, maxWidth, i === wordRows.length - 1)
29
);
30
};
31

32
const justifyText = (rowWords, maxWidth, isLastLine) => {
33
let spaces = maxWidth - rowWords.reduce((acc, curr) => acc + curr.length, 0);
34

35
if (rowWords.length === 1) {
36
return rowWords[0] + " ".repeat(spaces);
37
}
38

39
if (isLastLine) {
40
spaces -= rowWords.length - 1;
41
return rowWords.join(" ") + " ".repeat(spaces);
42
}
43

44
let index = rowWords.length - 1;
45
let justifiedWord = "";
46
while (rowWords.length > 0) {
47
const repeater = Math.floor(spaces / (rowWords.length - 1));
48
const word = rowWords.pop();
49

50
if (index === 0) {
51
justifiedWord = word + justifiedWord;
52
} else if (index === 1) {
53
justifiedWord = " ".repeat(spaces) + word + justifiedWord;
54
} else {
55
justifiedWord = " ".repeat(repeater) + word + justifiedWord;
56
}
57

58
index--;
59
spaces -= repeater;
60
}
61

62
return justifiedWord;
63
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0