0068.文本左右对齐

方法一:字符串模拟

时间复杂度 $O(m)$,空间复杂度 $O(1)$,其中 m 表示所有字符串的总长度。

// 放置以 index 结尾的 num 个单词,确保字符串长度为 maxWidth
func placestr(words []string, index, num, length, maxWidth int) string {
	if num == 1 {
		return words[index] + strings.Repeat(" ", maxWidth-length)
	}
	space, mod, substr := (maxWidth-length)/(num-1), (maxWidth-length)%(num-1), ""
	if index == len(words)-1 {
		space, mod = 1, maxWidth-length-num+1
	}
	for i := index - num + 1; i < index; i++ {
		numspace := space
		if mod > 0 && index != len(words)-1 {
			numspace, mod = numspace+1, mod-1
		}
		substr += words[i] + strings.Repeat(" ", numspace)
	}
	substr += words[index] + strings.Repeat(" ", mod)
	return substr
}

func fullJustify(words []string, maxWidth int) []string {
	ans, length, num := []string{}, 0, 0
	for i := 0; i < len(words); i++ {
		if length+len(words[i])+num <= maxWidth {
			length, num = length+len(words[i]), num+1
			continue
		}
		ans = append(ans, placestr(words, i-1, num, length, maxWidth))
		length, num = len(words[i]), 1
	}
	ans = append(ans, placestr(words, len(words)-1, num, length, maxWidth))
	return ans
}