-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext-justification.php
54 lines (46 loc) · 1.49 KB
/
text-justification.php
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
<?php
/**
* @link https://leetcode.com/problems/text-justification/
* @difficulty HARD
*/
class Solution
{
/**
* @param string[] $words
* @param int $maxWidth
* @return string[]
*/
public function fullJustify(array $words, int $maxWidth) : array
{
$result = [];
$i = 0;
while ($i < count($words)) {
$lineWords = [];
$lineWidth = 0;
while ($i < count($words) && $lineWidth + count($lineWords) + strlen($words[$i]) <= $maxWidth) {
$lineWords[] = $words[$i];
$lineWidth += strlen($words[$i]);
$i++;
}
$numWords = count($lineWords);
$numSpaces = $maxWidth - $lineWidth;
if ($i == count($words) || $numWords == 1) {
$line = implode(' ', $lineWords);
$line .= str_repeat(' ', $maxWidth - strlen($line));
} else {
$spacesBetweenWords = $numSpaces / ($numWords - 1);
$extraSpaces = $numSpaces % ($numWords - 1);
$line = '';
for ($j = 0; $j < $numWords - 1; $j++) {
$line .= $lineWords[$j] . str_repeat(' ', $spacesBetweenWords);
if ($j < $extraSpaces) {
$line .= ' ';
}
}
$line .= $lineWords[$numWords - 1];
}
$result[] = $line;
}
return $result;
}
}