-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0068-text-justification.js
More file actions
86 lines (74 loc) · 2.7 KB
/
0068-text-justification.js
File metadata and controls
86 lines (74 loc) · 2.7 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
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Text Justification
* Time Complexity: O(N * L)
* Space Complexity: O(N * L)
*/
var fullJustify = function (words, maxWidth) {
const resultLinesCollection = [];
let currentLineWordsBuffer = [];
let charsInCurrentBuffer = 0;
let wordIndexProgress = 0;
while (wordIndexProgress < words.length) {
const nextWordCandidate = words[wordIndexProgress];
const hypotheticalTotalLength =
charsInCurrentBuffer +
nextWordCandidate.length +
(currentLineWordsBuffer.length === 0 ? 0 : currentLineWordsBuffer.length);
if (hypotheticalTotalLength <= maxWidth) {
currentLineWordsBuffer.push(nextWordCandidate);
charsInCurrentBuffer += nextWordCandidate.length;
} else {
resultLinesCollection.push(currentLineWordsBuffer);
currentLineWordsBuffer = [nextWordCandidate];
charsInCurrentBuffer = nextWordCandidate.length;
}
wordIndexProgress++;
}
if (currentLineWordsBuffer.length > 0) {
resultLinesCollection.push(currentLineWordsBuffer);
}
const finalJustifiedOutput = [];
let lineProcessorIndex = 0;
while (lineProcessorIndex < resultLinesCollection.length) {
const lineWordsArray = resultLinesCollection[lineProcessorIndex];
const wordsOnThisLineCount = lineWordsArray.length;
let totalCharactersInWords = 0;
let charSumIterator = 0;
while (charSumIterator < wordsOnThisLineCount) {
totalCharactersInWords += lineWordsArray[charSumIterator].length;
charSumIterator++;
}
if (
lineProcessorIndex === resultLinesCollection.length - 1 ||
wordsOnThisLineCount === 1
) {
const leftJustifiedSegment = lineWordsArray.join(" ");
const additionalSpacesNeeded = maxWidth - leftJustifiedSegment.length;
finalJustifiedOutput.push(
leftJustifiedSegment + " ".repeat(additionalSpacesNeeded),
);
} else {
const totalSpacesToDistribute = maxWidth - totalCharactersInWords;
const numberOfGaps = wordsOnThisLineCount - 1;
const baseSpacesPerGap = Math.floor(
totalSpacesToDistribute / numberOfGaps,
);
let extraSpacesForLeftGaps = totalSpacesToDistribute % numberOfGaps;
let constructedLineString = lineWordsArray[0];
let wordPositionInLine = 1;
while (wordPositionInLine < wordsOnThisLineCount) {
let currentGapSpaces = baseSpacesPerGap;
if (extraSpacesForLeftGaps > 0) {
currentGapSpaces++;
extraSpacesForLeftGaps--;
}
constructedLineString +=
" ".repeat(currentGapSpaces) + lineWordsArray[wordPositionInLine];
wordPositionInLine++;
}
finalJustifiedOutput.push(constructedLineString);
}
lineProcessorIndex++;
}
return finalJustifiedOutput;
};