-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path068.js
More file actions
74 lines (69 loc) · 1.98 KB
/
068.js
File metadata and controls
74 lines (69 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
var fullJustify = function(words, maxWidth) {
let results = [];
let itemCount = 0;
let currentlength = 0;
let currentWords = [];
words.forEach(word => {
if (currentlength + itemCount * 1 + word.length <= maxWidth) {
currentWords.push(word);
currentlength += word.length;
itemCount += 1;
} else {
results.push(currentWords);
currentWords = [word];
itemCount = 1;
currentlength = word.length;
}
});
if (currentWords.length > 0) {
results.push(currentWords);
}
const getLineStr = (wordsInLine, isLastLine) => {
if (wordsInLine.length === 1) {
let word = wordsInLine[0];
spaceCount = maxWidth - word.length;
while(spaceCount > 0) {
word = word + " ";
--spaceCount;
}
return word;
} else if (isLastLine) {
let word = wordsInLine.join(" ");
spaceCount = maxWidth - word.length;
while(spaceCount > 0) {
word = word + " ";
--spaceCount;
}
return word;
} else {
let spaceCount = maxWidth - wordsInLine.reduce((sum, w) => {return sum + w.length}, 0);
let slotCount = wordsInLine.length - 1;
let value = Number.parseInt(spaceCount / slotCount);
spaceCount -= slotCount * value;
let slots = (new Array(slotCount)).fill(value);
let i = 0;
while(spaceCount > 0) {
slots[i] += 1;
--spaceCount;
++i;
}
let result = wordsInLine[0];
for (let i = 1; i < wordsInLine.length; ++i) {
result += ((new Array(slots[i - 1])).fill(" ").join("") + wordsInLine[i]);
}
return result;
}
}
if (results.length === 1) {
return results.map(wordsInLine => getLineStr(wordsInLine, true));
} else {
let lastOne = results[results.length - 1];
results.pop();
return results.map(wordsInLine => getLineStr(wordsInLine, false)).concat(getLineStr(lastOne, true));
}
};