<?phpclass Solution{ public $ret; /** * @param String[] $words * @param Integer $maxWidth * @return String[] */ public function fullJustify($words, $maxWidth) { // 按照贪心算法,归并每行所需元素 $line = []; $lineAddEmpty = []; for ($i = 0; $i < count($words); $i++) { $w = $words[$i]; if ($w > $maxWidth) return []; $lineHadStr = implode('', $line); if ($maxWidth < (strlen($lineHadStr) + strlen($w))) { $this->ret[] = $line; $line = []; } $line[] = $line ? ' ' . $w : $w; } $this->ret[] = $line; // 计算每行需要填充的 ' ' 数量 foreach ($this->ret as $k => $v) { $lineStrLen = 0; $lineEleCount = count($v); foreach ($v as $v2) { $lineStrLen += strlen($v2); } // 每行元素数量大于1时 if ($lineEleCount - 1) { $lineAddEmpty[$k]['perAddEmpty'] = floor(($maxWidth - $lineStrLen) / ($lineEleCount - 1)); $lineAddEmpty[$k]['moreAddEmpty'] = ($maxWidth - $lineStrLen) % ($lineEleCount - 1); } // 尾行 if ($k == count($this->ret) - 1) { $lineAddEmpty[$k]['perAddEmpty'] = 0; $lineAddEmpty[$k]['moreAddEmpty'] = $maxWidth - $lineStrLen; } } // 添加 ' ' ,使得字符串长度填充至 $maxWidth foreach ($this->ret as $k => $v) { if (!isset($lineAddEmpty[$k])) { continue; } $perAddEmpty = $lineAddEmpty[$k]['perAddEmpty'] ?? 0; foreach ($v as $k2 => $v2) { // 尾行特殊处理 if ($k == count($this->ret) - 1 && $k2 == count($v) - 1) { $this->ret[$k][$k2] = $this->ret[$k][$k2] . str_repeat(' ', $lineAddEmpty[$k]['moreAddEmpty'] - 1); } // 非尾行,首个位置不处理 if (($k < count($this->ret) - 1) && ($k2 == 0)) continue; $addEmpty = ($lineAddEmpty[$k]['moreAddEmpty'] > 0) ? str_repeat(' ', $perAddEmpty + 1) : str_repeat(' ', $perAddEmpty); if ($addEmpty === '') { break; } $lineAddEmpty[$k]['moreAddEmpty']--; $this->ret[$k][$k2] = $addEmpty . $this->ret[$k][$k2]; } } return $this->ret; }}$words = ["This", "is", "an", "example", "of", "text", "justification."];$maxWidth = 16;$cls = new Solution();$r = $cls->fullJustify($words, $maxWidth);array_walk($cls->ret, function (&$v) { $v = implode('', $v);});var_dump($cls->ret);