• [LeetCode]题解(python):068-Text Justification


    题目来源:

      https://leetcode.com/problems/text-justification/


    题意分析:

      输入一个字符串数组和一个规定长度L。将这个字符串数组的元素尽可能放到长度的L的字符串中,数组中的字符串不能拆开,一个长度L的字符串包括的若干个字符串之间用相等的空格间隔开。比如:

    words: ["This", "is", "an", "example", "of", "text", "justification."],L: 16.

    将返回

    [
       "This    is    an",
       "example  of text",
       "justification.  "
    ]

    题目思路:

      这道题目直接模拟解就可以了,要注意的是有很多细节要处理。从开始加入元素,长度增加,然后空格+1后继续加入新元素,直到长度大于L。然后判断空格的个数就可以了。


    代码(Python):

      

    class Solution(object):
        def fullJustify(self, words, maxWidth):
            """
            :type words: List[str]
            :type maxWidth: int
            :rtype: List[str]
            """
            ans = []
            i = 0
            while i < len(words):
                size,begin = 0,i
                while i < len(words):
                    if size == 0:
                        newsize = len(words[i])
                    else:
                        newsize = size + len(words[i]) + 1
                    if newsize <= maxWidth:
                        size = newsize
                    else:
                        break
                    i += 1
                s = maxWidth - size
                if i - begin - 1 > 0 and i < len(words):
                    ns = s / (i - begin - 1)
                    s %= i - begin - 1
                else:
                    ns = 0
                j = begin
                while j < i:
                    if j == begin: tmp = words[j]
                    else:
                        tmp += ' '*(ns + 1)
                        if s > 0 and i < len(words):
                            tmp += ' '
                            s -= 1
                        tmp += words[j]
                    j += 1
                tmp += ' '*s
                ans.append(tmp)
            return ans
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/5045245.html

  • 相关阅读:
    hibernate4.3.10使用注解映射方式样例
    eclipse ssh连接sqlserver express
    window2012 64bit 安装sqlserver2012 64bit调用excel的驱动安装
    SharpZipLib要支持unicode的文件名称
    搜索数据库中的内容
    AIX 添加开机启动项
    oracle 分区表和分区索引
    oracle 临时表学习
    oracle sys sysman system 介绍
    oracle to_date函数(转载)
  • 原文地址:https://www.cnblogs.com/chruny/p/5045245.html
Copyright © 2020-2023  润新知