68. 文本左右对齐

68. 文本左右对齐

方法一:模拟

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        res = []
        i, n = 0, len(words)
        while True: # 行循环
            first = i  # first 当前行首单词索引
            strLen = 0  # 当前行字符累计长度(不含空格)
            # 统计当前行单词数,加空格后长度 = 累计字符长度 + 当前单词长度 + 空格数(i - first)
            while i < n and strLen + (wordLen:=len(words[i])) + i - first <= maxWidth:
                strLen += wordLen
                i += 1 # 当条件不满足时 i 已经加一了

            # 1、先考虑最后一行,有只有一行的可能。
            if i == n:
                s = " ".join(words[first:])
                res.append(s + ' '*(maxWidth - len(s)))
                break

            wordNum = i - first # 当前行单词总数 
            spaceNum = maxWidth - strLen # 需要的空格数 

            # 2、只有一个单词
            if wordNum == 1:
                res.append(words[first] + ' '*spaceNum)
            else:
                # 3、多词需要分段处理
                avg, ext = divmod(spaceNum, wordNum - 1)
                # 需要窗外添加一个空格,共有 ext 个
                s1 = (' '*(avg + 1)).join(words[first:first + ext + 1])  
                s2 = (' '*avg).join(words[first + ext + 1:i])  
                res.append(s1 + ' '*avg + s2)

        return res
上一篇:allegro 测量器件间距68


下一篇:剑指 Offer 68 - I. 二叉搜索树的最近公共祖先(递归)