1. <?php
    2. class Solution
    3. {
    4. public $ret;
    5. /**
    6. * @param String[] $words
    7. * @param Integer $maxWidth
    8. * @return String[]
    9. */
    10. public function fullJustify($words, $maxWidth)
    11. {
    12. // 按照贪心算法,归并每行所需元素
    13. $line = [];
    14. $lineAddEmpty = [];
    15. for ($i = 0; $i < count($words); $i++) {
    16. $w = $words[$i];
    17. if ($w > $maxWidth) return [];
    18. $lineHadStr = implode('', $line);
    19. if ($maxWidth < (strlen($lineHadStr) + strlen($w))) {
    20. $this->ret[] = $line;
    21. $line = [];
    22. }
    23. $line[] = $line ? ' ' . $w : $w;
    24. }
    25. $this->ret[] = $line;
    26. // 计算每行需要填充的 ' ' 数量
    27. foreach ($this->ret as $k => $v) {
    28. $lineStrLen = 0;
    29. $lineEleCount = count($v);
    30. foreach ($v as $v2) {
    31. $lineStrLen += strlen($v2);
    32. }
    33. // 每行元素数量大于1时
    34. if ($lineEleCount - 1) {
    35. $lineAddEmpty[$k]['perAddEmpty'] = floor(($maxWidth - $lineStrLen) / ($lineEleCount - 1));
    36. $lineAddEmpty[$k]['moreAddEmpty'] = ($maxWidth - $lineStrLen) % ($lineEleCount - 1);
    37. }
    38. // 尾行
    39. if ($k == count($this->ret) - 1) {
    40. $lineAddEmpty[$k]['perAddEmpty'] = 0;
    41. $lineAddEmpty[$k]['moreAddEmpty'] = $maxWidth - $lineStrLen;
    42. }
    43. }
    44. // 添加 ' ' ,使得字符串长度填充至 $maxWidth
    45. foreach ($this->ret as $k => $v) {
    46. if (!isset($lineAddEmpty[$k])) {
    47. continue;
    48. }
    49. $perAddEmpty = $lineAddEmpty[$k]['perAddEmpty'] ?? 0;
    50. foreach ($v as $k2 => $v2) {
    51. // 尾行特殊处理
    52. if ($k == count($this->ret) - 1 && $k2 == count($v) - 1) {
    53. $this->ret[$k][$k2] = $this->ret[$k][$k2] . str_repeat(' ', $lineAddEmpty[$k]['moreAddEmpty'] - 1);
    54. }
    55. // 非尾行,首个位置不处理
    56. if (($k < count($this->ret) - 1) && ($k2 == 0)) continue;
    57. $addEmpty = ($lineAddEmpty[$k]['moreAddEmpty'] > 0) ? str_repeat(' ', $perAddEmpty + 1) : str_repeat(' ', $perAddEmpty);
    58. if ($addEmpty === '') {
    59. break;
    60. }
    61. $lineAddEmpty[$k]['moreAddEmpty']--;
    62. $this->ret[$k][$k2] = $addEmpty . $this->ret[$k][$k2];
    63. }
    64. }
    65. return $this->ret;
    66. }
    67. }
    68. $words = ["This", "is", "an", "example", "of", "text", "justification."];
    69. $maxWidth = 16;
    70. $cls = new Solution();
    71. $r = $cls->fullJustify($words, $maxWidth);
    72. array_walk($cls->ret, function (&$v) {
    73. $v = implode('', $v);
    74. });
    75. var_dump($cls->ret);