标签:pop last color text 分享图片 strong app form 要求
题目如下:
解题思路:解题方法没啥好说的,按题目要求来,最后一行左对齐,以及空格数不能被均分的时候,从左往右优先分配。
代码如下:
class Solution(object): def format(self,line,length,maxWidth,res): diff = maxWidth - length remainder = 0 if (len(line) - 1) > 1: interval = diff / (len(line) - 1) remainder = diff % (len(line) - 1) else: interval = diff w = ‘‘ for inx, val in enumerate(line): w += val if inx != len(line) - 1 or len(line) == 1: if remainder > 0: w += ‘ ‘ * (interval + 1) remainder -= 1 else: w += ‘ ‘ * (interval) res.append(w) def fullJustify(self, words, maxWidth): """ :type words: List[str] :type maxWidth: int :rtype: List[str] """ line = [] length = 0 res = [] for i,v in enumerate(words): if len(line) - 1 + length + len(v) >= maxWidth: self.format(line,length,maxWidth,res) line = [] length = 0 length += len(v) line.append(v) if len(line) > 0: self.format(line, length, maxWidth, res) last = res.pop(-1) last_char = None formats = ‘‘ for i in last: if last_char == ‘ ‘ and i == ‘ ‘: continue formats += i last_char = i formats += ‘ ‘ * (maxWidth - len(formats)) res.append(formats) return res
【leetcode】68. Text Justification
标签:pop last color text 分享图片 strong app form 要求
原文地址:https://www.cnblogs.com/seyjs/p/9499722.html