python3 解法

发布于 2021-04-17 02:24 ,所属分类:知识学习综合资讯

class Solution:    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:        lenth = 0        item = []        res = []        i = 0        while i < len(words):            lenth += len(words[i])            if lenth <= maxWidth:                item.append(words[i])                lenth += 1                i += 1                if i == len(words):                    item[-1] += ' ' * (maxWidth - lenth + 1)                    res.append(' '.join(item))            else:                plus = maxWidth - (lenth - len(words[i]) - len(item))#maxWidth-(lenth-len(words[i])-1)+(len(item)-1)#(lenth-len(words[i])-1)累计的长度#(len(item)-1)固有的单词间的空格                if len(item) == 1:                    item[0] += ' ' * (maxWidth - len(item[0]))                 else:                    for j in range(1, len(item)):                        item[j] = ' ' * int(plus/(len(item) - 1)) + item[j]                    tmp = plus%(len(item) - 1)                    for j in range(1, 1+tmp):                           item[j] = ' ' + item[j]                          res.append(''.join(item))                item = []                lenth = 0        return res


相关资源