https://leetcode.cn/problems/text-justification/description/?envType=study-plan-v2&envId=top-interview-150

 

package leetcode150

import (
    "testing"
)

func TestFullJustify(t *testing.T) {
    words := []string{"Science", "is", "what", "we", "understand", "well", "enough", "to", "explain", "to", "a", "computer.", "Art", "is", "everything", "else", "we", "do"}
    res := fullJustify(words, 20)
    for _, str := range res {
        println(str)
    }
    //time.Sleep(time.Second)
}

func fullJustify(words []string, maxWidth int) []string {
    ans := make([]string, 0)
    curStart, curLen, curWordTotal := 0, 0, 0
    for i := 0; i <= len(words); i++ {
        if i == len(words) {
            str := ""
            for j := curStart; j < i; j++ {
                if len(str) > 0 {
                    str += " "
                }
                str += words[j]
            }
            for j := len(str); j < maxWidth; j++ {
                str += " "
            }
            ans = append(ans, str)
            break
        }

        if curLen+len(words[i])+curWordTotal >= maxWidth {
            if curLen+len(words[i])+curWordTotal == maxWidth {
                curLen += len(words[i])
                curWordTotal++
                i++
            }
            str := ""
            fillSpace := maxWidth - curLen
            if curWordTotal != 1 {
                avgSpaceNum := fillSpace / (curWordTotal - 1)
                firstSpaceNum := fillSpace % (curWordTotal - 1)
                nSpace := 0
                for j := curStart; j < i; j++ {
                    str += words[j]
                    // 补空格
                    if nSpace < firstSpaceNum {
                        for t := 0; t < avgSpaceNum+1; t++ {
                            str += " "
                        }
                        nSpace++
                    } else if !(curWordTotal > 1 && j+1 == i) {
                        for t := 0; t < avgSpaceNum; t++ {
                            str += " "
                        }
                    }
                }
            } else {
                str += words[curStart]
                for t := 0; t < fillSpace; t++ {
                    str += " "
                }
            }

            ans = append(ans, str)
            // 重置
            curLen, curWordTotal = 0, 0
            curStart = i
            if i == len(words) {
                break
            }
        }
        curLen += len(words[i])
        curWordTotal++
    }

    return ans
}