-
Notifications
You must be signed in to change notification settings - Fork 0
/
fullJustify.js
67 lines (60 loc) · 1.48 KB
/
fullJustify.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
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
/** Justify a single line
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
var justifyLine = function (words, maxWidth) {
if (words.length == 1) {
let str = words[0];
for (i = str.length; i < maxWidth; i++) {
str += " "
}
return str;
}
let str = []
let strLength = 0;
for (let i = 0; i < words.length; i++) {
str.push(words[i]);
strLength += words[i].length
if (i != words.length - 1) {
str.push(" ")
strLength++;
}
}
while (strLength < maxWidth) {
for (let i = 1; i < str.length - 1; i += 2) {
str[i] += " ";
strLength++;
if (strLength === maxWidth) {
break;
}
}
}
return str.join("");
};
/** full justification of the text
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
var fullJustify = function (words, maxWidth) {
let result = [];
let currLine = [];
let currWidth = 0;
for (let i = 0; i < words.length; i++) {
if (currWidth + currLine.length + words[i].length <= maxWidth) {
currLine.push(words[i]);
currWidth += words[i].length;
} else {
result.push(justifyLine(currLine, maxWidth));
currLine = [words[i]];
currWidth = words[i].length;
}
}
let lastLine = currLine.join(" ");
for (i = lastLine.length; i < maxWidth; i++) {
lastLine += " "
}
result.push(lastLine);
return result;
};