【leetcode】68. Text Justification
阿新 • • 發佈:2018-08-20
end etc bsp interval tin 思路 object 代碼 最後一行
題目如下:
解題思路:解題方法沒啥好說的,按題目要求來,最後一行左對齊,以及空格數不能被均分的時候,從左往右優先分配。
代碼如下:
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