题意:

image.png

解题思路:

  1. 思路:

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String[] $words
  4. * @param Integer $maxWidth
  5. * @return String[]
  6. */
  7. function fullJustify($words, $maxWidth) {
  8. $start = 0;
  9. $ret = [];
  10. while ($start < count($words)) {
  11. $len = strlen($words[$start]);
  12. $next = $start + 1;
  13. while ($next < count($words)) {
  14. if (strlen($words[$next]) + $len + 1 > $maxWidth) break;
  15. $len += strlen($words[$next]) + 1;
  16. $next++;
  17. }
  18. $str = "";
  19. $str .= $words[$start];
  20. $space = $next - $start - 1;
  21. if ($next == count($words) || $space == 0) {
  22. for ($i = $start + 1; $i < $next; $i++) {
  23. $str .= " ";
  24. $str .= $words[$i];
  25. }
  26. for ($i = strlen($str); $i < $maxWidth; $i++) {
  27. $str .= " ";
  28. }
  29. } else {
  30. $space_num = floor(($maxWidth - $len) / $space);
  31. $carry = ($maxWidth - $len) % $space;
  32. for ($i = $start + 1; $i < $next; $i++) {
  33. $str .= " ";
  34. for ($k = $space_num; $k > 0; $k --) {
  35. $str .= " ";
  36. }
  37. if ($carry > 0) {
  38. $str .= " ";
  39. $carry--;
  40. }
  41. $str .= $words[$i];
  42. }
  43. }
  44. $start = $next;
  45. array_push($ret, $str);
  46. }
  47. return $ret;
  48. }
  49. }

GO代码实现: