leetcode 每日一题 68. 文本左右对齐

一维转二维再转一维

思路:

先根据最大长度条件把一维数组转换为二维数组,二维数组中的每个数组是结果中每个字符串包含的所有单词。再对二维数组中每个数组进行加空格处理,这里要注意的是,要对最后一行单独处理。

代码:

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        res = []
        temp = []
        path = []
        curWidth = 0
        for word in words:
            curwlen = len(word)
            if curWidth + curwlen +len(path) <= maxWidth:
                curWidth += curwlen
                path.append(word)
            else:
                temp.append(path[:])
                path.clear()
                curWidth = curwlen
                path.append(word)
        for wds in temp:
            wStr = self.jointWordToStr(wds,maxWidth)
            res.append(wStr)
        lastStr = path[0]
        for i in range(1,len(path)):
            lastStr = lastStr + ' ' + path[i]
        lastStr = lastStr + ' '*(maxWidth-len(''.join(path))-len(path)+1)
        res.append(lastStr)
        return res
    def jointWordToStr(self,words,maxWidth):
        listlen = len(words)
        if listlen == 1:
            return words[0]+ ' '*(maxWidth-len(words[0]))
        allAlp = 0 
        for i in range(listlen):
            allAlp += len(words[i])
        avespace = (maxWidth - allAlp)//(listlen-1)
        exspace = (maxWidth - allAlp)-avespace*(listlen-1)
        wStr = words[0]
        for i in range(exspace):
            wStr = wStr + ' '*(avespace+1)+words[i+1]
        for i in range(exspace,listlen-1):
            wStr = wStr + ' '*avespace + words[i+1]
        return wStr

 

posted @ 2020-06-09 22:25  nil_f  阅读(155)  评论(0)    收藏  举报