68.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import (
  3. "strings"
  4. )
  5. func fullJustify(words []string, maxWidth int) (ans []string) {
  6. beg, width := 0, -1
  7. for i := range words {
  8. if width+len(words[i]) >= maxWidth {
  9. // Arrange words in [beg, i)
  10. ans = append(ans, arrange(words, beg, i, width, maxWidth))
  11. // Reset status
  12. beg, width = i, -1
  13. }
  14. width += len(words[i]) + 1
  15. }
  16. // Arrange the last group of words,
  17. // the last line must be left-justified instead of fully-justified.
  18. prefix := strings.Join(words[beg:], " ")
  19. trail := strings.Repeat(" ", maxWidth-len(prefix))
  20. ans = append(ans, prefix+trail)
  21. return
  22. }
  23. func arrange(words []string, beg, end, width, maxWidth int) string {
  24. n := end - beg
  25. space := maxWidth - (width - n + 1)
  26. if n == 1 {
  27. return words[beg] + strings.Repeat(" ", space)
  28. }
  29. gap, remain := space/(n-1), space%(n-1)
  30. var sb strings.Builder
  31. for i := 0; i < n; i++ {
  32. sb.WriteString(words[beg+i])
  33. if space > 0 {
  34. sb.WriteString(strings.Repeat(" ", gap))
  35. space -= gap
  36. if i < remain {
  37. sb.WriteByte(' ')
  38. space--
  39. }
  40. }
  41. }
  42. return sb.String()
  43. }
  44. // func main() {
  45. // w := []string{"Science", "is", "what", "we", "understand", "well", "enough", "to", "explain",
  46. // "to", "a", "computer.", "Art", "is", "everything", "else", "we", "do"}
  47. // fmt.Println(fullJustify(w, 20))
  48. // w = []string{"What", "must", "be", "acknowledgment", "shall", "be"}
  49. // fmt.Println(fullJustify(w, 16))
  50. // }