-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
37 lines (32 loc) · 912 Bytes
/
index.js
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
/**
* Problem: https://leetcode.com/problems/text-justification/description/
*/
/**
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
var fullJustify = function(words, maxWidth) {
const result = [];
for (let i = 0; i < words.length;) {
let num = 0, len = 0;
while (i + num < words.length && words[i + num].length + len <= maxWidth - num) {
len += words[i + num].length;
++num;
}
let tmp = words[i];
for (let j = 1; j < num; ++j) {
if (i + num >= words.length)
tmp += ' ';
else {
for (let k = 0; k < parseInt((maxWidth - len) / (num - 1)) + (j <= (maxWidth - len) % (num - 1) ? 1 : 0); ++k) tmp += ' ';
}
tmp += words[i + j];
}
let extraSpaceCount = maxWidth - tmp.length;
for (let k = 0; k < extraSpaceCount; ++k) tmp += ' ';
result.push(tmp);
i += num;
}
return result;
};