-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path68.text-justification.js
72 lines (71 loc) · 1.82 KB
/
68.text-justification.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
68
69
70
71
72
/*
* @lc app=leetcode id=68 lang=javascript
*
* [68] Text Justification
*/
/**
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
/*
This is an example of text justification
*/
class Row {
constructor() {
this.items = [];
this.letters = 0;
}
}
var greedyAssignWordsToRows = function(words, maxWidth) {
let rows = [];
//using array as object
//[[letters:0]]
let firstItem = new Row();
rows[0] = firstItem;
for (let word of words) {
//using original row,res[0]
let row = rows[rows.length - 1];
//0&0 +0&4 > 16
// console.log(row.items.length, row.letters, row.items.length);
if (
row.items.length &&
row.letters + row.items.length + word.length > maxWidth
) {
// console.log("creating new row");
rows.push(new Row());
row = rows[rows.length - 1];
row.letters = 0;
}
//adding the word
row.items.push(word);
//and then add the count
row.letters += word.length;
}
// console.log("res", rows);
return rows;
};
var fullJustify = function(words, maxWidth) {
const rows = greedyAssignWordsToRows(words, maxWidth);
let res = [];
for (let r = 0; r < rows.length; r++) {
let row = rows[r];
// console.log("row", row);
if (row.items.length === 1 || r === rows.length - 1) {
res[r] =
row.items.join(" ") +
" ".repeat(maxWidth - row.letters - row.items.length + 1);
continue;
}
let line = row.items[0];
let spaces = maxWidth - row.letters;
let minSpaces = " ".repeat(Math.floor(spaces / (row.items.length - 1)));
let addSpace = spaces % (row.items.length - 1);
for (let w = 1; w < row.items.length; w++) {
line += minSpaces + (w <= addSpace ? " " : "") + row.items[w];
}
res[r] = line;
}
// console.log("the result", res);
return res;
};