leetcode 68 文本对齐

77 阅读2分钟

题意:

给定一个单词数组 words 和一个长度 maxWidth ,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。

你应该使用 “贪心算法” 来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。

要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。

文本的最后一行应为左对齐,且单词之间不插入额外的空格。

地址:leetcode.cn/problems/te…

思路分析:

其实就是简单的模拟题,注意一下边界情况. 很简单就能做出来,时间稍微有点久,不知道为什么会是hard难度题,思路很简单

代码:



import "strings"
func fullJustify(words []string, maxWidth int) []string {
    res := make([]string, 0)
    // 当 填充不进去的时候 填充空格
    // 单词之间先用一个空格占位 后续补充填充(对齐函数)
    // 填充空格
    str := ""
    for pos:=0;pos != len(words);pos++{
        nextStr := getNextStr(str, words[pos])
        nextStrLen := len(nextStr)
        if nextStrLen < maxWidth{
            str = nextStr
            continue
        }
        if nextStrLen == maxWidth{
            res = append(res, nextStr)
        }else{
            // 比目前的大. 那说明当前pos的不能取. 应该用上一个的字符串
            pos--
            // 排版
            if !strings.Contains(str, " "){
                strLen := len(str)
                for i:=0; i < maxWidth - strLen; i++{
                    str += " "
                }
                res = append(res, str)
            }else{
                addStr := fillSpace(maxWidth, str)
                res = append(res, addStr)
            }
            
        }
        str = ""
    }
    strLen := len(str)
    if strLen != 0 {
        for i:=0; i < maxWidth - strLen; i++{
            str += " "
        }
        res = append(res, str)
    }
    return res
}

func getNextStr(nowstr string, addStr string) string{
    if len(nowstr) != 0 {
        nowstr = nowstr + " "
    }
    return nowstr + addStr
}

func fillSpace(maxWidth int, str string)string{
    strList := strings.Split(str, " ")
    sumLen := 0
    for _, v := range strList {
        sumLen += len(v)
    }
    spaceStrList := make([]string, len(strList) - 1)
    leftLen := maxWidth - sumLen
    
    for pos := 0;leftLen != 0 && len(spaceStrList) != 0;pos++ {
        if pos == len(spaceStrList){
            pos = 0
        }
        spaceStrList[pos] += " "
        leftLen --
    }

    res := ""
    for i:=0;i<len(strList);i++{
       res += strList[i]
        if i != len(strList) -1 {
            res += spaceStrList[i]
        }
    }

    return res
}