zoukankan      html  css  js  c++  java
  • 【leetcode】68. Text Justification

    题目如下:

    解题思路:解题方法没啥好说的,按题目要求来,最后一行左对齐,以及空格数不能被均分的时候,从左往右优先分配。

    代码如下:

    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
            
  • 相关阅读:
    判断UpLoader是否安装了Flash
    事务
    AMQP
    分布式领域CAP理论
    查看数据库所有表的所有字段
    拼分页方法
    Website English Comments
    SQL语句执行时间测试
    一般处理程序返回json
    MVC Action返回Json
  • 原文地址:https://www.cnblogs.com/seyjs/p/9499722.html
Copyright © 2011-2022 走看看